Mert Zaim Mert Zaim - 6 months ago 22
PHP Question

Select words and count from long text (PHP)

I need to get hashtags and count them from a long text. I know I can do this with regex but I couldn't. If you can help me I'll appreciate it. Here's my example text;


#paris #love #spring #outdoor #life #istanbul #par #sacrecoeur #paris #france #latex #dog Thats what the world is, paris after all, an endless battle of contrasting memories. I can see clearly now the rain is gone. #music I can see all obstacles in my way. #paris #queenstreet #foreveronvocationNever felt more glamorous. #ski #music #skiing #skier #terrainpark #paris #snowboard #snowboarding #snowboarder #longboard #longboarding #longboarder #skateboard #skateboarder #skateboarding #winter #just my voice and my good friend Danny Marin will dj for our auditory exploration. #stack #over #flow to be or not to be #poem #music #paris


I need to get just hashtags like "#paris" and count each hashtags, finally order the hashtags by iteration. e.g.


#paris (6)

#music (3)

#... (2)

#... (2)

#...(1)

#...(1)

#...(1)


Edit: This the correct answer;



$query = mysql_query("select * from table order by column_name desc limit 5000");

$totalarray = array();

while($row=mysql_fetch_array($query)){
$text = $row["text"];

preg_match_all("/(\#\w+)/", $text, $array);
$totalarray = array_merge($totalarray, array_unique($array[1]));

}

$totalarray=array_count_values($totalarray);
arsort($totalarray);
$stack = array_slice($totalarray, 0, 10, true);
foreach($stack as $key => $value){

echo "$key ($value)<br>\n";
}




Answer
 preg_match_all("/(\#\w+)/", $string, $array);
$array = array_count_values($array[1]);
asort($array);

foreach($array as $key => $value) {
    echo "$key ($value)<br>\n";
}

Should give you what you need

Edit: sorry forgot the index of array

Working example:
http://sandbox.onlinephpfunctions.com/code/d1fe24cbc8deedd24f7825ea4e48eaa691b8d401

Comments