strrchr() Function Use in PHP 8.4 and PHP 8.5

The strrchr() function behaves identically in PHP 8.4 and PHP 8.5. There are no version-specific changes or deprecations for this function in either release. The most recent change to strrchr() was in PHP 8.3.0, which added the $before_needle parameter.

Function

strrchr() finds the last occurrence of a character (or the first character of a string) within another string and returns the portion of the haystack from that point to the end.

Signature:

strrchr(string $haystack, string $needle, bool $before_needle = false): string|false

Key Behavior:

  • Case-Sensitive: The search is strictly case sensitive.
  • Needle Handling: If $needle contains more than one character, only the first character is used for the search.
  • Return Value: Returns the substring starting from the last match, or false if the character is not found.

Examples

1. Basic Usage (File Extension Extraction).

This is the classic use case demonstrated in the official PHP manual.

<?php
$ext = strrchr( isomefile.txt , . );
echo "file extension: $ext "; 
// Outputs: file extension: .txt

$ext = $ext ? strtolower(substr($ext, 1)) : ;
echo "file extension: $ext";
// Outputs: file extension: txt
?>

It finds the last dot in the filename, ensuring that files like archive.tar.gz correctly identify .gz as the extension.

2. Using the $before_needle Parameter (PHP 8.3+).

Since PHP 8.3, you can retrieve the part of the string before the last match.

<?php
$path = /var/www/html/index.php ;
// Get the directory path (everything before the last slash)
$directory = strrchr($path, / , true);
echo $directory; 
// Outputs: /var/www/html
?>

This is useful for separating a filename from its directory path without needing dirname() or substr().

3. Multiple Occurrences.

<?php
$text = Hello, World ;
echo strrchr($text, o );
// Outputs: orld (from the o in "World", not the first o in "Hello")
?>

This confirms the "last occurrence" behavior.

Notes

  • Binary-Safe: The function is safe to use with binary data.
  • Needle as Integer: Passing an integer as $needle is no longer supported as of PHP 8.0.0. You must explicitly cast it to a string or use chr() if needed.
  • Related Functions: If you need the position (integer offset) of the last occurrence, use strrpos(). If you need the firstoccurrence, use strstr() or strchr().
5 Views