PHP strrpos() Function – Find the Last Occurrence of a Substring
This article explains PHP's strrpos() function, detailing its purpose, parameters, return values, and provides two practical code examples demonstrating how to locate the last occurrence of a substring with optional offsets in a string.
strrpos() calculates the position of the last occurrence of a needle string in a haystack string.
Explanation: Returns the numeric position of the needle in the haystack. In PHP 4 the needle must be a single character; if a string is given only its first character is used.
Parameters
haystack – The string to search in.
needle – The string to search for; if not a string it is converted to an integer character code.
offset – Optional offset; negative values start counting from the end of the string.
Return value
Returns the position of needle if found, or FALSE otherwise.
Example 1
<?php
$mystring = 'abcdefg';
$pos = strrpos($mystring, "b");
if ($pos === false) {
// not found...
}
?>Example 2
<?php
$foo = "0123456789a123456789b123456789c";
var_dump(strrpos($foo, '7', -5)); // start searching 5 characters from the end, result: int(17)
var_dump(strrpos($foo, '7', 20)); // start searching from position 20, result: int(27)
var_dump(strrpos($foo, '7', 28)); // result: bool(false)
?>Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
