PHP strrchr() Function: Syntax, Usage, Examples, and Case Sensitivity
The article explains PHP's strrchr() string function, detailing its syntax, parameters, return values, case‑sensitivity behavior, and provides multiple code examples demonstrating how to locate the last occurrence of a character or substring within a string.
Syntax of strrchr()
The strrchr() function is a PHP string function used to find the last occurrence of a specified character in a string and return that position together with all characters that follow it.
<code>strrchr(string $haystack, mixed $needle): string|false</code>In this signature, $haystack is the string to be searched, and $needle is the character or substring to look for.
Usage of strrchr()
Return Value
The function returns a string containing the portion of $haystack from the found character or substring to the end of the string. If the character or substring is not found, it returns false .
Example
Below is an example demonstrating how to use strrchr() :
<code>$str = "Hello, World!";
$lastComma = strrchr($str, ",");
echo $lastComma; // outputs: , World!</code>In this example, $str is the original string, $lastComma holds the result of strrchr() , which finds the last comma and the text after it, and echo prints , World! .
Searching for a Character or Substring
The strrchr() function can search for a single character or a multi‑character substring. The following code shows two scenarios:
<code>$str = "Hello, World!";
$lastComma = strrchr($str, ",");
echo $lastComma; // outputs: , World!
$str = "Hello, World!";
$lastWord = strrchr($str, "World");
echo $lastWord; // outputs: World!</code>In the first case the function searches for a comma, while in the second it searches for the substring "World". Whether searching for a character or a substring, strrchr() returns the found text together with everything that follows it.
Case Sensitivity
By default strrchr() is case‑sensitive, meaning a mismatch in case will cause the function to return false . For a case‑insensitive search you can use strripos() instead.
Summary
The strrchr() function is used to locate the last occurrence of a character or substring within a string and returns the portion of the string from that point to the end. It operates in a case‑sensitive manner unless you switch to a case‑insensitive alternative such as strripos() .
PHP Learning Recommendations
For further study, consider the following resources:
Vue3+Laravel8+Uniapp Beginner to Advanced Development Tutorial
Vue3+TP6+API Social E‑commerce System Development Course
Swoole From Beginner to Master Course
Workerman+TP6 Real‑time Chat System (Limited Time Offer)
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.