문제

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 개의 일치가 발견되었습니다

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top