PHP preg_match pour trouver plusieurs occurrences
-
19-09-2019 - |
Question
Quelle est la syntaxe correcte pour une expression régulière pour trouver plusieurs occurrences de la même chaîne avec preg_match en PHP?
Par exemple trouver si la chaîne suivante apparaît deux fois dans le paragraphe suivant:
$string = "/brown fox jumped [0-9]/";
$paragraph = "The brown fox jumped 1 time over the fence. The green fox did not. Then the brown fox jumped 2 times over the fence"
if (preg_match($string, $paragraph)) {
echo "match found";
}else {
echo "match NOT found";
}
La solution
Vous voulez utiliser preg_match_all()
. Voici à quoi il ressemblerait dans votre code. La fonction réelle renvoie le nombre d'objets trouvés, mais le tableau de $matches
tiendra les résultats:
<?php
$string = "/brown fox jumped [0-9]/";
$paragraph = "The brown fox jumped 1 time over the fence. The green fox did not. Then the brown fox jumped 2 times over the fence";
if (preg_match_all($string, $paragraph, &$matches)) {
echo count($matches[0]) . " matches found";
}else {
echo "match NOT found";
}
?>
Affichera:
2 correspondances trouvées
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow