Umair Zahid Umair Zahid - 2 years ago 56
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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download