PHP strrchr() Function: Description, Parameters, Return Value, and Usage Examples
This article explains the PHP strrchr() function, detailing its purpose of locating the last occurrence of a character in a string, describing its parameters and return value, and providing three practical code examples that demonstrate common usage scenarios.
Function Overview The string strrchr ( string $haystack , mixed $needle ) function searches for the last occurrence of a specified character (or the first character of a string) within the $haystack string and returns the portion of the string from that point to the end.
Explanation The function returns a substring of $haystack starting at the last occurrence of $needle. If $needle is not found, the function returns FALSE. When $needle contains more than one character, only its first character is considered, differing from strstr(). If $needle is not a string, it is converted to an integer and treated as an ASCII value.
Parameters
haystack : The string to be searched.
needle : The character or string to locate. If it is a string longer than one character, only the first character is used; non‑string values are cast to integers.
Return Value A substring of $haystack beginning with the last occurrence of $needle. If $needle is not found, FALSE is returned.
Example 1
<?php
$PATH = 'NAME:PASSWD:CHECK';
$dir = substr(strrchr($PATH, ':'), 1);
echo $dir; // 输出 CHECK
// 获取最后一行内容
$text = "Line 1
Line 2
Line 3";
$last = substr(strrchr($text, 10), 1);
echo $last; // 输出 line 3
?>Example 2
<?php
echo strrchr("I love Shanghai!", "Shanghai"); // 输出 Shanghai!
?>Example 3
<?php
echo strrchr("Hello world! What a beautiful day!", What); // 输出 What a beautiful day!
?>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.
