Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

What is the correct syntax for a regular expression to find multiple occurrences of the same string with preg_match in PHP?

For example find if the following string occurs TWICE in the following paragraph:

$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";
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
901 views
Welcome To Ask or Share your Answers For Others

1 Answer

You want to use preg_match_all(). Here is how it would look in your code. The actual function returns the count of items found, but the $matches array will hold the results:

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

Will output:

2 matches found


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...