要在PHP字符串中计算单词数,通常可以使用str_word_count函数,但我认为这并不总是一个好的解决方案。
好的示例:
$var ="Hello world!";
echo str_word_count($str);
print_r(str_word_count($str, 1));
-->输出
2
Array ( [0] => Hello [1] => world )
糟糕的例子:
$var ="The example number 2 is a bad example it will not
count numbers and punctuations !!";
-->输出:
14
Array ( [0] => The [1] => example [2] => number [3] => is [4] => a
[5] => bad [6] => example [7] => it [8] => will [9] => not
[10] => count [11] => numbers [12] => and [13] => punctuations )
有没有一个好的预定义函数可以正确地完成这个操作,还是必须使用 preg_match() ?
white-space
来计算有多少个空格? - akaBase$words = explode(' ', $var);
。 - Rimbleprint count(explode(' ', "hallo world"));//输出2 print count(explode(' ', "hallo world"));
//输出3 - Amani Ben Azzouz$words = array_filter(explode(' ', $var));
- Rimble