StirCrazy Posted July 22, 2007 Share Posted July 22, 2007 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 Link to comment https://forums.phpfreaks.com/topic/61291-solved-counting-keywords-from-an-array/ Share on other sites More sharing options...
GingerRobot Posted July 22, 2007 Share Posted July 22, 2007 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 ) Link to comment https://forums.phpfreaks.com/topic/61291-solved-counting-keywords-from-an-array/#findComment-304975 Share on other sites More sharing options...
StirCrazy Posted July 23, 2007 Author Share Posted July 23, 2007 Top bloke! cheers mate Link to comment https://forums.phpfreaks.com/topic/61291-solved-counting-keywords-from-an-array/#findComment-305082 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.