0

I have a paragraph. The paragraph contains normal words and also contains some link. This is for example :

@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

What i need is to count each words based on white space. So if there is a link, that link will be count as 1 word.

So the result will be like this : @zzz = 1, http://pbs.xx.com/xxx/x/xx_xx.jpg = 1, RT = 1 @yyyy_y: = 1, foto = 1, bareng = 1

And so on..

Is it possible ? How ?

Leonard Febrianto
  • 964
  • 2
  • 12
  • 37

2 Answers2

0

first clean extra space at the beginning and at the end with 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");

and thes try this:

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

These do not count if there is more than one space between words example:

'    word1 word2        word3    '  -> return 3

UPDATED To count how many times each word appears:

$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);
0

Maybe Helpful to you,

TRY THIS UPDATED CODE

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

OUTPUT

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
)
Soni Vimalkumar
  • 1,449
  • 15
  • 26