【问题标题】:Count Each Words Based on Whitespace PHP [closed]基于空格 PHP 计算每个单词 [关闭]
【发布时间】:2017-05-08 18:25:18
【问题描述】:

我有一个段落。该段落包含普通单词,还包含一些链接。例如:

@zzz http://pbs.xx.com/xxx/x/xx_xx.jpg  RT @yyyy_y: Foto Bareng zx, vc: Politik Boleh Beda Tapi Silaturahim Jalan Terus https://er.dfo/gffggf

我需要的是根据空格计算每个单词。因此,如果有链接,则该链接将计为 1 个单词。

所以结果会是这样的: @zzz = 1, http://pbs.xx.com/xxx/x/xx_xx.jpg = 1, RT = 1 @yyyy_y: = 1, 照片 = 1, bareng = 1

等等..

有可能吗?怎么样?

【问题讨论】:

标签: php


【解决方案1】:

也许对你有帮助,

试试这个更新后的代码

<?php
   $str = "@zzz http://pbs.xx.com/xxx/x/xx_xx.jpg  RT @yyyy_y: Foto Bareng zx, vc: Politik Boleh Beda Tapi Silaturahim Jalan Terus https://er.dfo/gffggf";

   $result = array_count_values(explode(' ', $str));
   arsort($result);// not neccesary
   echo "<pre>";print_r($result);exit;
?>

输出

Array
(
    [Tapi] => 1
    [Beda] => 1
    [Boleh] => 1
    [Silaturahim] => 1
    [Jalan] => 1
    [https://er.dfo/gffggf] => 1
    [Terus] => 1
    [Politik] => 1
    [vc:] => 1
    [RT] => 1
    [] => 1
    [http://pbs.xx.com/xxx/x/xx_xx.jpg] => 1
    [@yyyy_y:] => 1
    [Foto] => 1
    [zx,] => 1
    [Bareng] => 1
    [@zzz] => 1
)

【讨论】:

  • 我已经尝试过该代码。但是,我仍然希望该链接计为 1 个字
  • @Leonard Febrianto,请试试这个更新的代码。
  • @LeonardFebrianto,解决方案适合你吗?
  • 抱歉回复晚了。我得到了这个结果:[tco/0SE4HUUSkv@DianSamat pbstwimgcom/profile_images/713079390247264256/…@kompascom] => 1 [Sekolah] => 1
【解决方案2】:

首先用 TRIM() 清除开头和结尾的多余空间

$str = trim("@zzz http://pbs.xx.com/xxx/x/xx_xx.jpg  RT @yyyy_y: Foto Bareng zx, vc: Politik Boleh Beda Tapi Silaturahim Jalan Terus https://er.dfo/gffggf");

他们试试这个:

echo count(array_filter(explode(' ', $str)));

如果单词之间有多个空格,则这些不计算在内 示例:

'    word1 word2        word3    '  -> return 3

更新 计算每个单词出现的次数:

$str = trim("@zzz http://pbs.xx.com/xxx/x/xx_xx.jpg  RT @zzz Foto Bareng zx, vc: Politik Boleh Beda Tapi Silaturahim Jalan Terus https://er.dfo/gffggf");
$data = array_filter(explode(' ', $str));
$hash = Array();
foreach($data as $word){
    if(!key_exists($word, $hash))
        $hash[$word] = 0;
    $hash[$word]++;
}
print_r($hash);

【讨论】:

    猜你喜欢
    • 2012-10-16
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 2014-04-10
    • 2021-07-24
    • 2016-08-25
    • 2014-02-15
    • 1970-01-01
    相关资源
    最近更新 更多