2012-06-20 40 views
1

任何正则表达式大师在这里?这让我疯狂。preg_match查找字符串中单词的多个部分外观

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

我想数数“书”出现在此,返回的数量。

目前我有这里面是不工作:

$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里面应该成为$ VAR

任何一个知道如何正确地算?

回答

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"; 
} 
+0

谢谢你的澄清,我t检验thx,是的,我一直在看subtr_count,但它似乎并不适用于“书店”价值,它只是以某种方式计算“书” – Rubytastic

相关问题