如何计算PHP中特定字符串中的单词?

Was*_*jer 13 php string validation explode

我想计算特定字符串中的单词,因此我可以对其进行验证并阻止用户编写超过100个单词.

我写了这个函数,但是我觉得它不够有效,我使用了带空格的爆炸函数作为分隔符但是如果用户放置两个空格而不是一个空格怎么办.你能给我一个更好的方法吗?

function isValidLength($text , $length){

   $text  = explode(" " , $text );
   if(count($text) > $length)
          return false;
   else
          return true;
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*ita 22

也许str_word_count可以帮忙

http://php.net/manual/en/function.str-word-count.php

$Tag  = 'My Name is Gaurav'; 
$word = str_word_count($Tag);
echo $word;
Run Code Online (Sandbox Code Playgroud)

  • str_word_count很糟糕!如果它包含在像"主题""理论"等更大的单词中,它会多次计算"the".str_word_count糟透了,我在stackoverflow上看到它全部 (14认同)
  • @ giorgio79如何提供另类而不是像疯子一样咆哮. (7认同)

Mic*_*yen 10

您可以使用内置的PHP函数str_word_count.像这样使用它:

$str = "This is my simple string.";
echo str_word_count($str);
Run Code Online (Sandbox Code Playgroud)

这将输出5.

如果您计划在任何单词中使用特殊字符,则可以提供任何额外字符作为第三个参数.

$str = "This weather is like el ninã.";
echo str_word_count($str, 0, 'àáã');
Run Code Online (Sandbox Code Playgroud)

这将输出6.

  • @Blender:PHP真棒.您想要的只是标准库.只是这个小`makeBlog()`函数仍然缺失. (3认同)
  • 为什么PHP需要使用这么多功能......? (2认同)
  • 此函数不适用于非ascii字符(例如重音字母).str_word_count("déjà")输出2. (2认同)

Amr*_*Amr 10

试试这个:

function get_num_of_words($string) {
    $string = preg_replace('/\s+/', ' ', trim($string));
    $words = explode(" ", $string);
    return count($words);
}

$str = "Lorem ipsum dolor sit amet";
echo get_num_of_words($str);
Run Code Online (Sandbox Code Playgroud)

这将输出: 5

  • 到目前为止,这实际上是最好的答案,既简洁又没有某种严重的问题.但我会将函数体简化为`return count(explode('',preg_replace('/\s + /','',trim($ string))));`. (4认同)