问题描述
<?php
echo str_word_count(' - - - - - - - ');exit;
单词数为7,但没有单词。如何使此功能正常工作?
解决方法
如评论中所述,str_word_count
的行为可能很奇怪。
这里是使用简单的正则表达式来计算字数的另一种方法:
function count_words(string $string): int
{
return preg_match_all('/\b(?:[^\W\d_]|-)+\b/u',$string,$matches)
? count($matches[0])
: 0;
}
echo count_words(' - - - - - - - '),PHP_EOL; // 0
echo count_words('hello world'),PHP_EOL; // 2
echo count_words('hoho hé-hé haha'),PHP_EOL; // 3
echo count_words('hello 123'),PHP_EOL; // 1
当发现一系列字母时,这只是计算字符串的每次出现:
-
[^\W\d_]
基本上表示您可以在单词中找到的除连字符以外的任何字符, -
u
标志可确保将带重音符号的字符考虑在内。