phpstringstrrchr

Understanding strrchr function


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


Solution

  • 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