Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

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

strrpos($string,'@');

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

like image 865
Umair Zahid Avatar asked May 10 '16 05:05

Umair Zahid


People also ask

How do you find the last occurrence of a substring in a string?

strrchr() — Locate Last Occurrence of Character in String The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .

What is the last index position of a string?

Strings are zero-indexed: The index of a string's first character is 0 , and the index of a string's last character is the length of the string minus 1.

How do you get the last position of a substring in Python?

The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found.

How do I get the last Charindex in SQL?

If you want to get the index of the last space in a string of words, you can use this expression RIGHT(name, (CHARINDEX(' ',REVERSE(name),0)) to return the last word in the string. This is helpful if you want to parse out the last name of a full name that includes initials for the first and /or middle name.


1 Answers

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!';
}else
    echo $pos; //Output 9 this case
like image 72
Murad Hasan Avatar answered Oct 03 '22 04:10

Murad Hasan