Categories
PHP

Count Words Repetitions in PHP

Yesterday I wrote some functions for better SEO in PHP, but I realized that the Keywords are not so good.

I explain: Keywords should be the words that are more relevant in the text, but in the function It doesn’t work like that.

An idea can be to count the words and grab the top 25 ones.

To do this we can use this function I made for:

function countWords($text){//from the given text
	$text = strip_tags($text);//erase possible html tags
	$text = strtolower($text);//everything to lower case
	$text = str_replace (array('rn', 'n', '+'), ',', $text);//replace possible returns
	$text = str_replace (array('–','(',')',':','.','?','!','_','*','-'), '', $text);//replace not valid character
	$text = str_replace (array(' ','.'), ',', $text);//replace for comas

	$wordCounter=array();//array to keep word->number of repetitions

	$arrText=explode(",",$text);//create array with words
	unset($text);
	foreach ($arrText as $value)  {
		$value=trim($value);//bye spaces
		if ( strlen($value)>0 ) {//no smaller than 1
			if (array_key_exists($value,$wordCounter)){//if the key exists we ad 1 more
				$wordCounter[$value]=$wordCounter[$value]+1;
			}
			else $wordCounter[$value]=1;//creating the key
		}
	}
	unset($arrText);

	uasort($wordCounter,"cmp");//short from bigger to smaller

	$keywords="
    "; foreach($wordCounter as $key=>$value){ $keywords.="
  1. ".$key." => ".$value."
  2. "; } $keywords.="
"; unset($wordCounter); return $keywords; } function cmp($a, $b) {//sort for uasort descendent numbers if ($a == $b) return 0; return ($a < $b) ? 1 : -1; }

This function will return a sorted list with the words.

Here you can find an example

I also need to say that works really fast 😉

And soon (I think tomorrow) I will release a php Class for better SEO including this improvement.