I'm doing some tests with function strrchr, but I can't understand the output:
$text = 'This is my code';
echo strrchr($text, 'my');
//my code
Ok, the function returned the string before last occurrence
$text = 'This is a test to test code';
echo strrchr($text, 'test');
//t code
But in this case, why the function is returning "t code", instead "test code"?
Thanks
The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string . If the given character is not found, a NULL pointer is returned.
The C library function char *strrchr(const char *str, int c) searches for the last occurrence of the character c (an unsigned char) in the string pointed to, by the argument str.
strrchr() function In C++, strrchr() is a predefined function used for string handling. cstring is the header file required for string functions. This function returns a pointer to the last occurrence of a character in a string.
strdup() :This function returns a pointer to a null-terminated byte string, which is a duplicate of the string pointed to by s. The memory obtained is done dynamically using malloc and hence it can be freed using free(). It returns a pointer to the duplicated string s.
Simple! Because it finds the last occurrence of a character in a string. Not a word.
It just finds the last occurrence character and then it will echo
the rest of the string from that position.
In your first example:
$text = 'This is my code';
echo strrchr($text, 'my');
It finds the last m
and then prints the reset included m
itself: my code
In your second example:
$text = 'This is a test to test code';
echo strrchr($text, 'test');
It finds the last t
and like the last example prints the rest: test code
More info
From the PHP documentation:
needle
If needle contains more than one character, only the first is used. This behavior is different from that of strstr().
So your first example is the exact same as:
$text = 'This is my code';
echo strrchr($text, 'm');
RESULT
'This is my code'
^
'my code'
Your second example is the exact 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 I made does what you were expecting:
/**
* Give the last occurrence of a string and everything that follows it
* in another string
* @param String $needle String to find
* @param String $haystack Subject
* @return String String|empty string
*/
function strrchrExtend($needle, $haystack)
{
if (preg_match('/(('.$needle.')(?:.(?!\2))*)$/', $haystack, $matches))
return $matches[0];
return '';
}
The regex it uses can be tested here: DEMO
example:
echo strrchrExtend('test', 'This is a test to test code');
OUTPUT:
test code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With