preg_match在字符串中查找单词的多个部分外观

时间:2012-06-20 15:06:58

标签: php count preg-match preg-match-all

这里有任何正则表达的大师吗?它让我疯狂。

说我有这个字符串: “书店预订”

我想计算出现的数字“书籍”并返回数字。

目前我有这个不起作用:

$string = "bookstore books Booking";            
if (preg_match_all('/\b[A-Z]+books\b/', $string, $matches)) {
  echo count($matches[0]) . " matches found";
} else {
  echo "match NOT found";
}

除此之外,preg_match_all中的“books”应该变成$ var

任何人都知道如何正确计算?

1 个答案:

答案 0 :(得分:1)

实际上要简单得多,你可以像这样使用preg_match_all()

$string = "bookstore books Booking";   
$var = "books";      
if (preg_match_all('/' . $var . '/', $string, $matches)) {
    echo count($matches[0]) . " matches found";
} else {
    echo "match NOT found";
}

或者使用为此目的而制作的功能substr_count()

$string = "bookstore books Booking";   
$var = "books";      
if ($count = substr_count($string, $var)) {
    echo $count . " matches found";
} else {
    echo "match NOT found";
}
相关问题