7

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

viniciuswebdev
  • 1,286
  • 1
  • 11
  • 20
  • 3
    From the [PHP docs](http://www.php.net/manual/en/function.strrchr.php), `If needle contains more than one character, only the first is used.` In your first case, that letter is `m`, in the second case, it's `t` – Mark Baker Sep 28 '14 at 21:49
  • 2
    @MarkBaker, that really needs to be an answer rather than a comment , perhaps with a source linked :) – Moo-Juice Sep 28 '14 at 21:49

3 Answers3

2

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

Sky
  • 4,244
  • 7
  • 54
  • 83
2

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
Community
  • 1
  • 1
Adam Sinclair
  • 1,654
  • 12
  • 15
0

From PHP doc :

haystack The string to search in

needle If needle contains more than one character, only the first is used. This behavior is different from that of strstr().

In your example, only the first character of your needle (t) will be used

nicolas
  • 712
  • 4
  • 15