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
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 ) 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.