stripos

(PHP 5, PHP 7, PHP 8)

stripos Findet das erste Vorkommen eines Teilstrings in einem String, unabhängig von Groß- und Kleinschreibung

Beschreibung

stripos ( string $haystack , string $needle , int $offset = 0 ) : int|false

Sucht die numerische Position des ersten Vorkommens von needle innerhalb des Strings haystack.

Im Gegensatz zu strpos() ist stripos() unabhängig von Groß- und Kleinschreibung.

Parameter-Liste

haystack

Die Zeichenkette, in der gesucht werden soll.

needle

Beachten Sie, dass needle eine Zeichenkette von einem oder mehreren Zeichen sein kann.

Wenn der Parameter needle keine Zeichenkette ist, wird er vor PHP 8.0.0 in eine Ganzzahl umgewandelt und als ordinaler Wert eines Zeichens betrachtet. Dieses Verhalten gilt seit PHP 7.3.0 als veraltet und es wird dringend empfohlen, sich nicht darauf zu verlassen. Ist das Verhalten gewünscht, so sollte needle explizit in eine Zeichenkette umgewandelt werden oder explizit die Funktion chr() aufgerufen werden.

offset

Wenn angegeben, dann beginnt die Suche diese Anzahl an Zeichen gezählt vom Beginn des Strings. Ist der Offset negativ, beginnt die Suche diese Anzahl von Zeichen gezählt vom Ende der Zeichenkette.

Rückgabewerte

Gibt die Position, an der sich die Needle befindet, relativ zum Beginn der haystack Zeichenkette zurück (unabhängig vom Offset). Es ist zu beachten, dass Stringpositionen mit 0, und nicht mit 1 beginnen.

Gibt false zurück, wenn die Needle nicht gefunden wurde.

Warnung

Diese Funktion kann sowohl das boolsche false zurückliefern, als auch einen nicht-boolschen Wert, welcher zu false ausgewertet wird. Weitere Informationen entnehmen Sie bitte dem Abschnitt über die boolschen Typen. Benutzen Sie deshalb den === Operator, um den Rückgabewert dieser Funktion zu überprüfen.

Changelog

Version Beschreibung
8.0.0 Die Übergabe eines Integer als needle wird nicht mehr unterstützt.
7.3.0 Die Übergabe eines Integer als needle wird missbilligt.
7.1.0 Unterstützung für negative offset-Werte wurde hinzugefügt.

Beispiele

Beispiel #1 stripos()-Beispiele

<?php
$findmich  
'a';
$meinstring1 'xyz';
$meinstring2 'ABC';

$pos1 stripos($meinstring1$findmich);
$pos2 stripos($meinstring2$findmich);

// 'a' ist natürlich nicht in 'xyz' enthalten
if ($pos1 === false) {
    echo 
"Die Zeichenkette '$findmich' kommt nicht im String '$meinstring1' vor.";
}

// Beachten Sie die Verwendung von ===. Ein einfaches == funktioniert nicht wie
// erwartet, da 'a' an Position 0 (also erster!) Stelle steht
if ($pos2 !== false) {
    echo 
"Die Zeichenkette '$findmich' wurde in '$meinstring2' an Position $pos2 gefunden";
}
?>

Anmerkungen

Hinweis: Diese Funktion ist binary safe.

Siehe auch

  • mb_stripos() - Finds position of first occurrence of a string within another, case insensitive
  • str_contains() - Determine if a string contains a given substring
  • str_ends_with() - Checks if a string ends with a given substring
  • str_starts_with() - Checks if a string starts with a given substring
  • strpos() - Sucht die Position des ersten Vorkommens des Suchstrings in einem String
  • strrpos() - Findet die Position des letzten Vorkommens eines Teilstrings innerhalb einer Zeichenkette
  • strripos() - Findet das letzte Vorkommen der gesuchten Zeichenkette in einem String, unabhängig von Groß- und Kleinschreibung
  • stristr() - Wie strstr, aber unabhängig von Groß- bzw. Kleinschreibung
  • substr() - Gibt einen Teil eines Strings zurück
  • str_ireplace() - Groß- und kleinschreibungsunabhängige Version von str_replace

add a note add a note

User Contributed Notes 8 notes

up
39
emperorshishire at gmail dot com
15 years ago
I found myself needing to find the first position of multiple needles in one haystack.  So I wrote this little function:

<?php
function multineedle_stripos($haystack, $needles, $offset=0) {
    foreach(
$needles as $needle) {
       
$found[$needle] = stripos($haystack, $needle, $offset);
    }
    return
$found;
}

// It works as such:
$haystack = "The quick brown fox jumps over the lazy dog.";
$needle = array("fox", "dog", ".", "duck")
var_dump(multineedle_stripos($haystack, $needle));
/* Output:
   array(3) {
     ["fox"]=>
     int(16)
     ["dog"]=>
     int(40)
     ["."]=>
     int(43)
     ["duck"]=>
     bool(false)
   }
*/
?>
up
3
sorrynorealemail at example dot com
5 years ago
Unlike strpos() it seems that stripos() does NOT issue a WARNING if the needle is an empty string ''.
up
3
spam at kleppinger dot com
9 years ago
Regarding the function by spam at wikicms dot org

It is very bad practice to use the same function name as an existing php function but have a different output format.  Someone maintaining the code in the future is likely to be very confused by this.  It will also be hard to eradicate from a codebase because the naming is identical so each use of stripos() would have to be analyzed to see how it is expecting the output format (bool or number/bool).

Calling it string_found() or something like that would make a lot more sense for long-term use.
up
1
Ian Macdonald
8 years ago
Regarding the === note, it might be worth clarifying that the correct tests for a binary found/not found condition are  !==false to detect found, and ===false to detect not found.
up
0
emanuel dot karlsson at rolfsbuss dot se
5 years ago
Finding numbers in strings requires you to cast the number to string first.

strpos("123", 2) !== strpos("123", "2")
up
-15
steve at opilo dot net
10 years ago
A handy function if you need to adjust layout based on whether or not a string contains descending letters:

<?php function containsDescenders($text) {
   
$descenders = array("g","j","p","q","y");
    foreach (
$descenders as $letter) {
        if (
stripos($text,$letter) !== false) {
            return
true;
        }
    }
    return
false;
}
?>
up
-20
spam at wikicms dot org
10 years ago
If you like using ternary operator, I wrote simple example how to use stripos function.
Also, in my example I add "How to use namespaces" for wide knowledges for newbies.

<?php
namespace My;

//You can be free using core functions in your NameSpaces (My)
function stripos($haystack, $needle) {
   
//To call core function (from global NS) you should add backslash only - \func
   
return (FALSE === \stripos($haystack, $needle)) ? FALSE : TRUE;
}

var_dump(stripos($haystack = 'John knows English language.', $needle = 'john')); //TRUE
var_dump(stripos($haystack = 'Sara knows English language too.', $needle = 'john')); //FALSE
?>
up
-20
grf at post dot cz
17 years ago
this would to work with any language, i hope.
tested on czech (eastern europe) lang.

<?php
/****************************************
*    SAFE HIGHLIGHT
****************************************/
/**
* function finds and encase every string in a $needleArr array with
* strings $shearLft (from the left side) and $shearRgt (guess from which
* side).
* already encased needles are IGNORED for any other step, so order
* of needles in $needleArr is pretty important.
*
* function is searching needles in case-insensitive mode,
* but case in the subject is saved.
*
* can you do it better? so, do it.
*
* @param array $needleArr array of needles
* @param string $shearLft left shear
* @param string $shearRgt right shear
* @param string $subject subject
* @param string $encoding encoding ('utf-8' is default)
*
* @author griffin
*/
function safeHighlight( $needleArr, $shearLft, $shearRgt, $subject, $encoding = 'utf-8')
{
   
   
// encoding
   
$e = $encoding;
   
   
// oh, no needles
   
if( !is_array( $needleArr))
        return
$subject;
       
   
// empty keys throw-off, only unique, reindex
   
$nA = array_values(
           
array_unique(
               
array_diff( $needleArr, array(''))
            )
        );
   
   
// needle count
   
if( !($nC = count( $nA)))
        return
$subject; // nothing to hl
       
    // shear length
   
if( !(($rLL = mb_strlen( $rL = $shearLft, $e))
    + (
$rRL = mb_strlen( $rR = $shearRgt, $e))))
        return
$subject; // no shears
   
    // subject length
   
if( !($sL = mb_strlen( $s = $subject, $e)))
        return
null; // empty subject
       
    // subject in lowercase (we need to aviod
    // using mb_stripos due to PHP version)
   
$sW = mb_strtolower( $s, $e);
   
   
// masking ~ 0=not changed, 1=changed
   
$m = str_repeat( '0', $sL);
   
   
// loop for each needle
   
for( $n=0; $n<$nC; $n++)
    {
       
       
// needle string loWercase
       
$nW = mb_strtolower( $nA[ $n], $e);
       
       
$o = 0; // offset
       
$nL = mb_strlen( $nW, $e); // needle length

        // search needle
       
while( false !== ($p = mb_strpos( $sW, $nW, $o, $e)))
        {
           
// oh hurrey, needle found on $p position
           
            // is founded needle already modified? (in full-length)
           
for( $q=$p; $q<($p+$nL); $q++)
                if(
$m[ $q])
                {
                   
// ai, caramba. already modified, jump over
                   
$o+= $nL;
                   
                   
// continue for while() loop - not for for() loop!
                   
continue 2;
                }
           
           
// explode subject and mask into three parts
            // partA|needle|partB
           
$sE[0] = mb_substr( $s, 0, $p, $e);
           
$sE[1] = mb_substr( $s, $p, $nL, $e);
           
$sE[2] = mb_substr( $s, $p+$nL, $sL-$p-$nL, $e);
           
           
// mask
            // partA|partB (needle not needed)
           
$mE[0] = mb_substr( $m, 0, $p, $e);
           
$mE[1] = mb_substr( $m, $p+$nL, $sL-$p-$nL, $e);
           
           
// apply shears
           
$sE[1] = $rL.$sE[1].$rR;
           
           
// update sunject length
           
$sL+= $rLL + $rRL;
           
           
// update mask
           
$m = $mE[0] . str_repeat( '1', $rLL + $nL + $rRL) . $mE[1];
           
           
// implode into a subject
           
$s = implode( $sE);
           
           
// update lowercase subject
           
$sW = mb_strtolower( $s, $e);
           
           
// increase offset
           
$o+= $rLL + $nL + $rRL;
           
           
// end of string reached
           
if( $o>=$sL)
                break;
           
        }
// while()
       
   
} // for( $n=0; $n<$nC; $n++)
   
    // oouu yeaaa, kick the subject out of the function
   
return $s;
   
}
// function safeHighlight()
/****************************************
*    END: SAFE HIGHLIGHT
****************************************/
?>
To Top