Umair Zahid Umair Zahid - 5 months ago 5x
PHP Question

find the position of last occurrence of sub string in a string with limit of ending index

I have a string like

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

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

Currently i am using


Third parameter of strrpos will be starting index, can we give ending index?


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

For your purpose, you need to explode your string with $ and start the application of strrpos for the first index of exploded array.

Try this:

$string="abc @def @xyz $ @def @xyz";
$strArr = explode('$', $string);
$pos = strrpos($strArr[0], "@");

if ($pos === false) { // note: three equal signs
    echo 'Not Found!';
    echo $pos; //Output 9 this case