PHP如何计算一个字符串中的单词数?
给定一个包含一些单词的字符串,任务是计算字符串的单词数 PHP的str 。为了完成这项任务,我们有以下方法:
方法一:使用str_word_count ()方法: str_word_count ()方法用于统计一个字符串的单词数。
语法:
str_word_count(string, return, char)
例子:
PHP
PHP
PHP
0) {
$str = str_replace(" ", " ", $str);
}
return substr_count($str, " ")+1;
}
$str = " Geeks for Geeks ";
// Function call
$len = get_num_of_words($str);
// Printing the result
echo $len;
?>
3
方法2:这里的想法是使用trim() , preg_replace() , count() 和explode()方法。
Step 1: Remove the trailing and leading white spaces using the trim() method and remove the multiple whitespace into a single space using preg_replace() method.
Step 2: Convert the string into an array using the explode() method.
Step 3: Now count() method counts the number of elements in an array.
Step 4: Resultant is the number of words in a string.
例子:
PHP
3
方法 3:这里的想法是使用trim() , substr_count()和str_replace() 方法。
Step 1: Remove the trailing and leading white spaces using the trim() method.
Step 2: Convert the multiple white spaces into single space using the substr_count() and str_replace() method.
Step 3: Now counts the number of word in a string using substr_count($str, ” “)+1 and return the result.
例子:
PHP
0) {
$str = str_replace(" ", " ", $str);
}
return substr_count($str, " ")+1;
}
$str = " Geeks for Geeks ";
// Function call
$len = get_num_of_words($str);
// Printing the result
echo $len;
?>
3