PHP strrchr() Function: Description, Parameters, Return Value, and Usage Examples
The article explains PHP's strrchr() function, detailing its syntax, parameter behavior, return values, and provides two practical code examples demonstrating how to retrieve the last occurrence of a character or substring within a string.
The strrchr() function in PHP searches for the last occurrence of a specified character (or the first character of a string) within a given haystack string and returns the portion of the haystack starting from that position to the end.
Syntax: string strrchr(string $haystack, mixed $needle)
Return value: If the needle is found, the function returns the substring from the needle's last occurrence to the end of the haystack; otherwise it returns FALSE .
Parameters:
haystack : The string to be searched.
needle : If a string, only its first character is used; if not a string, it is converted to an integer and treated as an ASCII value.
Example 1:
<?php
echo strrchr("Hello world!", 101);
echo "\n\r";
// Get the last line content
$text = "Line 1\nLine 2\nLine 3";
$last = substr(strrchr($text, 10), 1);
echo $last;
?>This example demonstrates retrieving the substring after the last newline character (ASCII 10) in a multi‑line string.
Example 2:
<?php
echo strrchr("Hello world! What a beautiful day!", What);
?>The second example shows using a string as the needle, where only the first character of the needle ("W") is considered, returning the portion of the haystack from the last "W" onward.
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.