Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使正则表达式将特定单词作为整个单词计算?_Php_Regex - Fatal编程技术网

Php 如何使正则表达式将特定单词作为整个单词计算?

Php 如何使正则表达式将特定单词作为整个单词计算?,php,regex,Php,Regex,如何使正则表达式将特定单词作为整个单词而不是单词的一部分来计算? 例如: $str = "Brains Brainsgdfgdfgdfgfdg"; // 1 count of word echo substr_count($str, "Brains"); 输出: 2 1 我试过这样做: $str = "Brains Brains Brainsasdasdas Brains"; // 3 count of word echo substr_count($str, " Brains ");

如何使正则表达式将特定单词作为整个单词而不是单词的一部分来计算? 例如:

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

2
1
我试过这样做:

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

2
1
我需要给出该结果的表达式:

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

4
试试这个

$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;

一种方法是使用要在单词边界内作为一个完整单词计算的单词来拆分字符串,即在正则表达式中使用\b作为分隔符。preg_split将返回一个数组,其中的值比出现的单词多一个,因此答案就是该数组的计数减去一。e、 g

$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

那你试过什么正则表达式?你只列出了子问题。这些答案中有一个解决了你的问题吗?如果是,请在向上/向下投票箭头下方的绿色箭头中标记答案。否则,您可以提供更多信息来帮助解决问题。请参阅ps,如果这对您有帮助,请将其视为正确答案