mb_strrpos
mb_strrpos($haystack, $needle, $offset, $encoding)
Returns the position of the last occurrence of the searched text, counted in characters from zero. When the text is not found, it returns false. It is the variant of the strrpos() function for text with accents.
Parameters
- $haystack – the text to search in.
- $needle – the text to look for.
- $offset – optional. A positive number: the search starts from this position. A negative number: the search ends that many characters before the end of the text.
- $encoding – optional, the character encoding. The default is the value of mb_internal_encoding(), usually UTF-8.
Examples
// the position in characters, strrpos returns the position in bytes
echo mb_strrpos("café and café", "café"); // 9
echo strrpos("café and café", "café"); // 10
var_dump(mb_strrpos("café", "x")); // bool(false)
// the part after the last separator
$path = "Home > Recipes > Crème brûlée";
echo mb_substr($path, mb_strrpos($path, ">") + 2); // Crème brûlée
// shortening text to a whole word: cut it and go back to the last space
$text = "Crème brûlée and café au lait";
$short = mb_substr($text, 0, 18);
echo $short; // Crème brûlée and c
echo mb_substr($short, 0, mb_strrpos($short, " ")) . "…"; // Crème brûlée and…
// a positive offset: the search starts from the fifth position
echo mb_strrpos("a-b-c-d", "-", 4); // 5
// a negative offset: the last three characters are left out
echo mb_strrpos("a-b-c-d", "-", -3); // 3
Things to watch out for
- Compare the result with !== false. Position 0 behaves as false in an ordinary condition.
- The position is in characters. Use it only with mb_ functions, and a position from strrpos() only with functions without mb_.
- When shortening to a whole word, expect text without a space. mb_strrpos then returns false and mb_substr() with the length false (that is 0) returns an empty string.
- It is case-sensitive. mb_strripos() searches regardless of case.
- pathinfo() returns a file extension more reliably.
Related functions:
strrpos()
mb_strpos()
mb_substr()