MENU
Searching
To find the position of $s2 in $s1, use:strpos($s1,$s2[,$i=0]);
stripos($s1,$s2[,$i=0]);
strrpos($s1,$s2[,$i=0]);
strripos($s1,$s2[,$i=0]);
FALSE is returned if $s2 cannot be found. ‘i’ performs a case-insensitive search. ‘r’ searches for the last instead of the first occurrence. $i denotes the starting position of the search. For strrpos(……) and strripos(……), if $i is negative, the search will start -$i characters from the end, searching backwards.
Notice the use of ===. FALSE and 0 are equivalent in values but not in types.
PHP 8.0 added three straightforward string-search functions that replace old, easy-to-get-wrong idioms.<!DOCTYPE html><html><head></head>
<body><?php
echo strpos("abcabc","abc",1);
echo stripos("abcabc","ABC",1);
echo strrpos("abcabc","abc",-4);
echo strripos("abcabc","ABC",-4);
echo "<br/>";
if (strpos("aaa","bb")===FALSE) echo "string not found";
?></body></html>3300
string not found
string not found
str_contains($s1,$s2) returns true if $s2 occurs anywhere in $s1, replacing strpos($s1,$s2)!==false.
str_starts_with($s1,$s2) returns true if $s1 begins with $s2, replacing strpos($s1,$s2)===0.
str_ends_with($s1,$s2) returns true if $s1 ends with $s2.
All three return a plain boolean, so there is no need for the error-prone === / !== comparison against FALSE that strpos() requires.
str_contains(), str_starts_with(), and str_ends_with() return a plain boolean, avoiding the === FALSE gotcha.
<!DOCTYPE html><html><head></head>
<body><?php
$s = "The quick brown fox";
// old idioms
var_dump(strpos($s, "quick") !== false);
var_dump(strpos($s, "The") === 0);
// PHP 8.0+
var_dump(str_contains($s, "quick"));
var_dump(str_starts_with($s, "The"));
var_dump(str_ends_with($s, "fox"));
?></body></html>bool(true)
bool(true)
bool(true)
bool(true)
bool(true)