Comment trouver la deuxième (ou la nième) occurrence d'une chaîne avec strpos ?

Mary-Kate Olsen
Libérer: 2024-10-18 14:49:03
original
337 Les gens l'ont consulté

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";
Copier après la connexion

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal