Reader Level:
ARTICLE

Identifying Duplicate Word in a String Using PHP

Posted by Vinod Kumar Articles | PHP March 19, 2013
In this article I will explain how to identify duplicate words in a string.
  • 0
  • 0
  • 2212

Introduction

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.

Example

 

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.

 

<?php

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

{

 $wordStats[strtolower($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.

Output

duplicate word.1jpg.jpg

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.

Syntax

array_unique (array)

 

Parameter Description
The input array Takes an input array and returns a new array without duplicate values.

 

Example

<?php

$input = array("a" => "green", "red", "b" => "green", "blue", "red");

$result = array_unique($input);

echo "<pre>";print_r($result);

?>

Output

duplicate word.jpg

COMMENT USING