如何制作将特定单词视为整个单词的正则表达式?

时间:2018-08-25 05:16:27

标签: php regex

如何制作将特定单词视为整个单词而将作为单词一部分的正则表达式? 例如:

$str = "Brains Brainsgdfgdfgdfgfdg"; // 1 count of word
echo substr_count($str, "Brains");

输出:

2

我试图这样做:

$str = "Brains Brains Brainsasdasdas Brains"; // 3 count of word
echo substr_count($str, " Brains ");

输出:

1

我需要可以给出该结果的表达式:

$str = "Brains Brains.Brains, Brainsasdasdas and another one Brains." // 4 count of word
// echo count of brains of $str with the expression

输出应为:

4

2 个答案:

答案 0 :(得分:1)

尝试

$str = "Brains Brains.Brains, Brainsasdasdas and another one Brains."; 
$count = 0 ;
$words =  preg_split("/[\s,\.]+/", $str );
foreach ($words as $word) {
    if ($word == "Brains"){
        $count++;
    }
}
echo $count;

答案 1 :(得分:0)

一种方法是使用preg_split根据要计数的单词(作为整个单词边界内的整个单词,即在正则表达式中使用\b)来拆分字符串)作为分隔符。 preg_split将返回一个数组,该数组中的值比单词出现的次数多,因此答案只是该数组的count,减一。例如

$str = "Brains Brains.Brains, Brainsasdasdas and another one Brains.";
echo count(preg_split('/\bBrains\b/', $str))-1;
$str = "Brains Brains Brainsasdasdas Brains";
echo count(preg_split('/\bBrains\b/', $str))-1;
$str = "Brains Brainsgdfgdfgdfgfdg";
echo count(preg_split('/\bBrains\b/', $str))-1;

输出

4
3
1