Jump to content

[SOLVED] counting keywords from an array


StirCrazy

Recommended Posts

Hi folks,

Wonder if someone can give me a hand :)

 

If I had a variable like this:-

$contents = "test keyword1 test test keyword1 test test test test test keyword2 test test test test test test keyword3 test test test test test test test keyword3 test test test test keyword1 test test test test test keyword3 test";

and an array like this:-

Array ([0] => test [1] => keyword1 [2] => keyword2 [3] => keyword3)

 

 

How would I find out how many times each word in the array features in $contents ?

 

The preferable return would be an array like this:-

array('test' => 21, 'keyword1' => 3, 'keyword2' => 1, 'keyword3' => 3);

 

Any help would be great :)

 

Thanks in advance :D

Link to comment
https://forums.phpfreaks.com/topic/61291-solved-counting-keywords-from-an-array/
Share on other sites

Use the substr_count() function:

 

<?php
$contents = "test keyword1 test test keyword1 test test test test test keyword2 test test test test test test keyword3 test test test test test test test keyword3 test test test test keyword1 test test test test test keyword3 test";
$array = Array ('test','keyword1','keyword2','keyword3');
$newarray = array();
foreach($array as $value){
	$newarray[$value] = substr_count($contents,$value);
}
print_r($newarray);
?>

 

Produces:

 

Array ( [test] => 31 [keyword1] => 3 [keyword2] => 1 [keyword3] => 3 ) 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.