How to Find the Second (or nth) Occurrence of a String with strpos?

Mary-Kate Olsen
Release: 2024-10-18 14:49:03
Original
241 people have browsed it

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";
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!