From the PHP documentation :
needles
If the needle contains more than one character, only the first is used . This behavior is different from strstr ().
So your first example is the same as:
$text = 'This is my code'; echo strrchr($text, 'm');
RESULT
'This is my code' ^ 'my code'
Your second example is the same as:
$text = 'This is a test to test code'; echo strrchr($text, 't');
RESULT
'This is a test to test code' ^ 't code'
This function that I did does what you expected:
function strrchrExtend($needle, $haystack) { if (preg_match('/(('.$needle.')(?:.(?!\2))*)$/', $haystack, $matches)) return $matches[0]; return ''; }
The regex used can be tested here: DEMO
An example :
echo strrchrExtend('test', 'This is a test to test code');
OUTPUT
test code
source share