strrchr(): Finding the Last Occurrence of a Character / sub-string in a String
1. What is strrchr()?
The PHP strrchr() function is used to find the last occurrence of a character in a string and returns the part of the string from that character onwards. Syntax:
- $haystack: The input string to search within.
- $needle: The character to search for.
- Return Value: It returns the portion of the string starting from the last occurrence of the needle (including the needle itself). If the needle is not found, it returns `false`.
2. Example 1: Basic Usage
The example below demonstrates how to find the last occurrence of a character in a string:
Searching for 'O' (uppercase) would not match with lowercase o inside World since it is case-sensitive.
7. Comparing strrchr() and strchr()
While strrchr() finds the last occurrence of a character, strchr() (or its alias strstr()) finds the first occurrence of a character. Here’s a comparison:
Using strrchr():
$text = "Hello world, welcome to PHP";
$result = strrchr($text, 'o');
echo $result; // Output: "o PHP"
$result = strchr($text, 'o');
echo $result; // Output: "o world, welcome to PHP"
8. Best Practices for strrchr()
- Extracting File Extensions: Use strrchr() to easily get file extensions from filenames.
- String Parsing: When working with log files, URLs, or file paths, strrchr() can be used to extract relevant information, such as the last directory or domain name.