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)
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.
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