这里有任何正则表达的大师吗?它让我疯狂。
说我有这个字符串: “书店预订”
我想计算出现的数字“书籍”并返回数字。
目前我有这个不起作用:
$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
任何人都知道如何正确计算?
答案 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";
}