14

PHPでpreg_matchを使用して同じ文字列の複数の出現を見つけるための正規表現の正しい構文は何ですか?

たとえば、次の文字列が次の段落で 2 回出現するかどうかを調べます。

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

1 に答える 1

40

を使用しますpreg_match_all()。これがあなたのコードでどのように見えるかです。実際の関数は見つかったアイテムの数を返しますが、$matches配列には結果が保持されます。

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

出力します:

2 件の一致が見つかりました

于 2010-01-08T19:12:06.187 に答える