Find the position of the last occurrence of a substring in a string with an index end limit

I have a line like

$string="abc @def @xyz $ @def @xyz"; 

Now I want to get the index of the last occurrence of @ before $.

I am currently using

 strrpos($string,'@'); 

The third parameter strrpos will be the starting index, is it possible to specify the ending index?

+5
source share
2 answers

Using strrpos you can get the last occurrence. More on function.strrpos

For your purpose, you need to blow your string with $ and run the strrpos application for the first index in the parsed array.

Try the following:

 $string="abc @def @xyz $ @def @xyz"; $strArr = explode('$', $string); $pos = strrpos($strArr[0], "@"); if ($pos === false) { // note: three equal signs echo 'Not Found!'; }else echo $pos; //Output 9 this case 
+5
source

Another alternative: -

 $string="abc @def @xyz $ @def @xyz"; $pos = strrpos($string, '@', -strrpos($string, '$')); if($pos === false){ echo 'Not Found!'; }else{ echo $pos; // 9 } 

Note : - A negative sign returns the index of the last character '@' before the $ sign.

+2
source

All Articles