How to:Find duplicate words in a string[PHP]

By

January 2, 2011PHP1 Comment

We can find duplicate words in a string through Wordstats() in PHP.In following code , first i have compressed multiple spaces into string and then decomposed the sentence into words with explode().

Atlast i have used wordstats() to find stats of word in a string.

Output will be g2.

?php
//define the string
$str="Devlup is the part of G2 Networks g2";
//trim the whitespace
$str=trim($str);
//compress the whitespace
$str=ereg_replace('[[:space:]]+', ' ',$str);
//decompose the string into array of words
$words=explode(' ',$str);
//count occurence of each word
foreach($words as $w)
{
$wordstats[strtolower($w)]++;
}
//print all duplicate words
foreach($wordstats as $k=>$v)
{
	if($v>=2)
	{
		print "$k \r\n";
	}
}
?>

Related posts:

One Response to “How to:Find duplicate words in a string[PHP]”
  1. Sanjay

    Nice Tutorial but
    ereg_replace() is deprecated.

Leave a Reply