在 PHP 字符串中计算所有单词,包括数字

8

要在PHP字符串中计算单词数,通常可以使用str_word_count函数,但我认为这并不总是一个好的解决方案。

好的示例:

$var ="Hello world!";
echo str_word_count($str);
print_r(str_word_count($str, 1));

-->输出

   2
   Array ( [0] => Hello [1] => world ) 

糟糕的例子:

$var ="The example number 2 is a bad example it will not 
count numbers  and punctuations !!";

-->输出:

  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 ) 

有没有一个好的预定义函数可以正确地完成这个操作,还是必须使用 preg_match() ?

可能使用 white-space 来计算有多少个空格? - akaBase
1
你可以使用 $words = explode(' ', $var); - Rimble
@TomKriek 不行,这个解决方案不好,因为我的输入可能在两个单词之间有多个空格。print count(explode(' ', "hallo world"));//输出2 print count(explode(' ', "hallo world")); //输出3 - Amani Ben Azzouz
抱歉,在第二个示例中,我的先前评论中的额外空格已被删除。 - Amani Ben Azzouz
1
尝试这样写:$words = array_filter(explode(' ', $var)); - Rimble
@TomKriek 好主意,它有效果 - Amani Ben Azzouz
8个回答

7
您可以通过空格将字符串分割并计算结果:
$res = preg_split('/\s+/', $input);
$count = count($res);

使用您的字符串

"The example number 2 is a bad example it will not 
count numbers  and punctuations !!"

这段代码将生成16

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


explode(' ', $string) 不总是有效,因为我的数据存储在数据库中,我无法确定每个单词之间是否有一个或多个空格,但第一种解决方案始终有效。 - Amani Ben Azzouz

6
以下使用 count()explode(), 将输出:

在此行中的数字1被计算,并且它包含以下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";

?>

编辑:

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

<?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.";

?>

工作但带有异常,如果在单词之间添加一些额外的空格,计数将增加。 - Amani Ben Azzouz
@Amani 我明白了,谢谢你的回复,很高兴看到你从Aleks那里得到了解决方案,干杯 :) - Funk Forty Niner
@Amani 我已经进行了一次编辑,在这个版本中,额外的空格和标点符号将不会被计算。 - Funk Forty Niner
1
感谢您提供的解决方案。对于这个编辑,我给一个加一的赞。 - Amani Ben Azzouz
@Amani 非常感谢您的提问。请保留已接受的答案。我只是想让我的回答更好,因为我最初没有考虑到可能存在的额外空格(和标点符号)。干杯,谢谢 :) 我希望它也能对您有所帮助。这是一个很好的问题。+1 - Funk Forty Niner

1

在字符串中最常用的计算单词数的方法是通过任何类型的空白字符进行分割:

count(preg_split('~\s+~u', trim($text)))

这里,'~\s+~u' 用任何一个或多个Unicode空白字符分割整个文本。 缺点是 !! 被认为是一个单词。 如果你想计算字母和数字单词(即仅由字母或数字组成的文本字符串),你应该考虑使用 preg_match_all
if (preg_match_all('~[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?|\d+|(?>\p{L}\p{M}*+)+~u', $text, $matches)) {
    return count($matches[0]);
}

请查看正则表达式演示PHP演示

$re = '~[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?|\d+|(?>\p{L}\p{M}*+)+~u';
$text = "The example number 2 is a bad example it will not \ncount numbers  and punctuations !! X is 2.5674.";
if (preg_match_all($re, $text, $matches)) {
    echo count($matches[0]);
} // 18 in this string

[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)? 正则表达式是一个众所周知的整数或浮点数正则表达式,而 (?>\p{L}\p{M}*+)+ 则匹配任何一个或多个字母 (\p{L}),每个字母后面都可以跟随任意数量的变音标记 (\p{M}*+)。

正则表达式详解

  • [-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)? - 可选的 -+,0个或多个 ASCII 数字,可选的 .,1个或多个 ASCII 数字,可选的 eE 序列,可选的 -+,然后是 1 个或多个 ASCII 数字
  • | - 或
  • \d+ - 任意 1 个或多个 Unicode 数字
  • | - 或
  • (?>\p{L}\p{M}*+)+ - 1 个或多个 Unicode 字母后跟任意 0 个或多个变音符号。

如果您只想计算仅由数字和字母(带变音符号)组成的文本块(以任意顺序混合),您也可以使用

'~[\p{N}\p{L}\p{M}]+~u'

请查看另一个正则表达式演示, \p{M}匹配变音符号,\p{N}匹配数字,\p{L}匹配字母。


0

你也可以使用下面的代码,它对我有效。

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

    $string="php string word count in simple way";
    echo $count=get_num_of_words($string);

结果将会是7


0

我知道这个问题很旧了,但我仍然想分享我采用的解决方法。

$str ="Hello world !";
// you can include allowed special characters  as third param.
print_r(str_word_count($str, 1, '!'));

代码输出为

Array ( [0] => Hello [1] => world [2] => ! )

如果你想要包含更多的单词,可以在第三个参数中指定。

print_r(str_word_count($str, 1, '0..9.~!@#$%^&*()-_=+{}[]\|;:?/<>.,'));

从 0..9。将包括所有数字,并单独插入其他特殊字符。


0
使用 count(explode(' ', $var));

这个不好的解决方案也是如此,因为我的输入可能在两个单词之间有多个空格。print count(explode(' ', "hallo world"));//输出2 print count(explode(' ', "hallo world")); //输出3 PS:第二个字符串中的第二个空格会自动从我的注释中删除。 - Amani Ben Azzouz

0

只是对你的解决方案进行了一些改进

function stringWordNumberCount($text){
    if (!$text) {
        return 0;
    }

    //Clean the text to remove special character
    $text = trim(preg_replace('/[^A-Za-z0-9\-]/', ' ', $text));

    //Remove continus space on text
    $text = trim( preg_replace('/\s+/', ' ',$text));

    //count space
    return count(explode(' ', $text));

}

-1

答案:

function limit_text($text, $limit) {
    if(str_word_count($text, 0) > $limit) {
        $words = str_word_count($text, 2);
        $pos = array_keys($words);
        $text = substr($text, 0, $pos[$limit]) . '...';
    }
    return $text;
}

如果您使用该类,您将添加这个。 - Ramkumar Chandrasekar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接