Identifying Duplicate Word in a String Using PHP
In this article I will explain how to identify duplicate words in a string.
In this article I will explain how to identify duplicate words in a string. You want to identify words that appear more than once in a string. Decompose the string into individual words, and then count the occurrences of each word.
Here the first task is identifying the real words in the sentences or paragraph. You do that by compressing multiple spaces, and then decomposing the sentence into words with the explode() function, using a single space as the delimiter.
$str = ("Hello I Am Am Lekhu Lekhu and Vinod Vinod");
$str = trim($str);
// compress the whitespace in the middle of the string
$str = ereg_replace('[[:space:]]+', ' ', $str);
$words = explode(' ', $str);
// save stats to another array
foreach ($words as $w)
// print all duplicate words
foreach ($wordStats as $k=>$v)
if ($v >= 2)
print "Duplicate word is <b>$k</b>"."<br>";
The $wrdstat variable, is initialized and a key is created within it for every word in the original string. If a word occurs more than once then the value corresponding to that word's key in the $wrdstat array is incremented by one.
And in the next example I will explain use of a function. This function is named "array_unique()" and the array unique function finds duplicate words in a array.
|The input array ||Takes an input array and returns a new array without duplicate values.|
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);