PHP birden fazla kopyasını bulmak için preg_match

1 Cevap php

PHP preg_match ile aynı dize birden fazla kopyasını bulmak için bir düzenli ifade için doğru sözdizimi nedir?

Aşağıdaki dize aşağıdaki paragrafta iki kez meydana Örneğin bulabilirsiniz:

$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";
}

1 Cevap

Sen preg_match_all() . Here is how it would look in your code. The actual function returns the count of items found, but the $matches dizisi sonuçları yapacak kullanmak istiyorsanız:

<?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";
}
?>

Çıktısı:

Bulunan 2 maç