Home >Backend Development >PHP Tutorial >How to Find the Second (or nth) Occurrence of a String with strpos?
Finding the Second Occurrence of a String with strpos
The strpos() function is a handy tool for locating the first occurrence of a substring within a string. However, if you need to retrieve the second or subsequent occurrences, the standard strpos() syntax falls short. Here's a creative workaround:
A custom function, strposX(), can be implemented to accomplish this task. It takes the haystack (the string in which we want to find the occurrence), the needle (the substring to locate), and the number of the occurrence you desire to find.
The strposX() function follows a recursive approach. If the desired occurrence number is 1, it simply calls strpos() to find the first occurrence. For subsequent occurrences (number greater than 1), it calls itself recursively to find the previous occurrence (nth-1) and adds the length of the needle to that position to shift the starting point of the search for the nth occurrence.
Here's an example of how to use the strposX() function:
$haystack = "PHP Programming is Fun"; $needle = "Programming"; $nthOccurrence = 2; $occurrence = strposX($haystack, $needle, $nthOccurrence); echo "The $nthOccurrence occurrence of '$needle' is at position $occurrence";
This code will output: "The 2nd occurrence of 'Programming' is at position 8".
By applying this custom strposX() function, you can easily retrieve the nth occurrence of any substring within a string, making your code more versatile and efficient.
The above is the detailed content of How to Find the Second (or nth) Occurrence of a String with strpos?. For more information, please follow other related articles on the PHP Chinese website!