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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP strrpos() Function – Find the Last Occurrence of a Substring

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)
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendprogrammingstring-functionsstrrpos
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.