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?
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 .
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.
The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With