PHPは複数の出現を見つけるためにするpreg_match
-
19-09-2019 - |
質問
PHPでするpreg_matchと同じ文字列の複数の出現を見つけるための正規表現のための正しい構文は何ですか?
次の文字列は、次の段落で二度発生した場合、たとえば見つけます:
$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";
}
解決
あなたは 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試合見つかっ
所属していません StackOverflow