计算所有单词,包括php字符串中的数字

Ama*_*ouz 6 php

为了计算php字符串中的单词,通常我们可以使用str_word_count,但我认为并不总是一个好的解决方案

好例子:

$var ="Hello world!";
echo str_word_count($str);
print_r(str_word_count($str, 1));
Run Code Online (Sandbox Code Playgroud)

- >输出

   2
   Array ( [0] => Hello [1] => world ) 
Run Code Online (Sandbox Code Playgroud)

坏例子:

$var ="The example number 2 is a bad example it will not 
count numbers  and punctuations !!";
Run Code Online (Sandbox Code Playgroud)

- >输出:

  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 ) 
Run Code Online (Sandbox Code Playgroud)

是否有一个很好的预定义函数来正确执行此操作,还是必须使用preg_match()?

Ale*_*s G 6

您始终可以按空格拆分字符串并计算结果:

$res = preg_split('/\s+/', $input);
$count = count($res);
Run Code Online (Sandbox Code Playgroud)

用你的字符串

"The example number 2 is a bad example it will not 
count numbers  and punctuations !!"
Run Code Online (Sandbox Code Playgroud)

此代码将产生16.

使用它的优点explode(' ', $string)是它可以处理多行字符串以及制表符,而不仅仅是空格。缺点是比较慢。


Fun*_*ner 6

以下使用count()explode(),将回应:

The number 1 in this line will counted and it contains the following count 8

PHP:

<?php

$text = "The number 1 in this line will counted";

$count = count(explode(" ", $text));

echo "$text and it contains the following count $count";

?>
Run Code Online (Sandbox Code Playgroud)

编辑:

旁注:
可以修改正则表达式以接受标准集中未包含的其他字符.

<?php

$text = "The numbers   1  3 spaces and punctuations will not be counted !! . . ";

$text = trim(preg_replace('/[^A-Za-z0-9\-]/', ' ', $text));

$text = preg_replace('/\s+/', ' ', $text);


// used for the function to echo the line of text
$string = $text;

    function clean($string) {

       return preg_replace('/[^A-Za-z0-9\-]/', ' ', $string);

    }

echo clean($string);

echo "<br>";

echo "There are ";
echo $count = count(explode(" ", $text));
echo " words in this line, this includes the number(s).";

echo "<br>";

echo "It will not count punctuations.";

?>
Run Code Online (Sandbox Code Playgroud)