Understanding the strrchr Function

I am doing some tests with strrchr function, but I can not understand the output:

$text = 'This is my code'; echo strrchr($text, 'my'); //my code 

Ok, the function returned the string to the last occurrence

 $text = 'This is a test to test code'; echo strrchr($text, 'test'); //t code 

But in this case, why does the function return a "t-code" instead of a "test code"?

thanks

+6
source share
3 answers

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:

 /** * 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 used can be tested here: DEMO

An example :

 echo strrchrExtend('test', 'This is a test to test code'); 

OUTPUT

 test code 
+1
source

Simple! Because he finds the last occurrence of a character in line. Not a word.

It just finds the last character of the entry, and then it will echo rest of the line from that position.


In the first example:

 $text = 'This is my code'; echo strrchr($text, 'my'); 

It finds the last m , and then prints reset m : 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

Additional Information

+2
source

From a PHP doc:

stack String to search in

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

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

-1
source

Source: https://habr.com/ru/post/975978/


All Articles