stripos
stripos($haystack, $needle, $offset)
Returns the position of the first occurrence of the text $needle in the string (counted from zero) and ignores the difference between uppercase and lowercase letters. When it does not find the text, it returns false. It is the counterpart of strpos().
Parameters
- $haystack – the string to search in.
- $needle – the text to look for.
- $offset – optional, the position to start searching from. A negative number counts from the end of the string.
Examples
var_dump(stripos("Garth.cz", "GARTH")); // int(0)
var_dump(stripos("Garth.cz", ".CZ")); // int(5)
var_dump(stripos("Garth.cz", "x")); // bool(false)
// strpos is case-sensitive
var_dump(strpos("Garth.cz", "garth")); // bool(false)
// the “contains?” test – comparing with false including the type
if (stripos("Garth.cz", "garth") !== false) {
echo "Found"; // Found
}
// searching from a given position
var_dump(stripos("Abc abc", "a", 1)); // int(4)
// a negative offset – it searches only in the last three characters
var_dump(stripos("Abc abc", "B", -3)); // int(5)
// it does not treat an uppercase and a lowercase accented letter as the same
var_dump(stripos("Crème BRÛLÉE", "brûlée")); // bool(false)
// mb_stripos handles text with accents (it returns the position in characters)
var_dump(mb_stripos("Crème BRÛLÉE", "brûlée")); // int(6)
Things to watch out for
- Always compare the result with !== false. When the searched text is right at the start, the function returns 0 and an ordinary condition would take it as “not found”.
- It ignores letter case only for letters without accents. For text with accents use mb_stripos().
- The position is in bytes, mb_stripos() returns the position in characters. For text with accents the two numbers differ, so do not use the result of one function as a position for functions of the other group.
- For an empty search text PHP 7 returns false, PHP 8 the position where the search starts (0 without an offset).
Related functions:
strpos()
strripos()
stristr()
mb_stripos()