I understand that this function will get the first occurrence of the string.
But what I want is the 2nd occurrence.
How to go about doing that?
Simplest solution for this specific case is to use the offset parameter: $pos = strpos($info, '-', strpos($info, '-') + 1);
The strpos() function finds the position of the first occurrence of a string inside another string. Note: The strpos() function is case-sensitive. Note: This function is binary-safe.
strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.
Search for string inside another string - strstrThe function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string.
I know this question is kind of old, but here's a function I wrote to get the Xth occurrence of a substring, which may be helpful for other people that have this issue and stumble over this thread.
/** * Find the position of the Xth occurrence of a substring in a string * @param $haystack * @param $needle * @param $number integer > 0 * @return int */ function strposX($haystack, $needle, $number) { if ($number == 1) { return strpos($haystack, $needle); } elseif ($number > 1) { return strpos($haystack, $needle, strposX($haystack, $needle, $number - 1) + strlen($needle)); } else { return error_log('Error: Value for parameter $number is out of range'); } }
Or a simplified version:
function strposX($haystack, $needle, $number = 0) { return strpos($haystack, $needle, $number > 1 ? strposX($haystack, $needle, $number - 1) + strlen($needle) : 0 ); }
You need to specify the offset for the start of the search as the optional third parameter and calculate it by starting the search directly after the first occurrence by adding the length of what you're searching for to the location you found it at.
$pos1 = strpos($haystack, $needle); $pos2 = strpos($haystack, $needle, $pos1 + strlen($needle));
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