PHP preg_match di trovare più occorrenze
-
19-09-2019 - |
Domanda
Qual è la sintassi corretta per un'espressione regolare per trovare più occorrenze della stessa stringa con preg_match in PHP?
Ad esempio trovare se la seguente stringa si verifica due volte nel paragrafo seguente:
$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";
}
Soluzione
Si desidera utilizzare preg_match_all()
. Ecco come dovrebbe apparire nel codice. La funzione attuale restituisce il numero di elementi trovati, ma la matrice $matches
terrà i risultati:
<?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";
}
?>
output sarà:
2 partite trovati
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow