-2

I need to find out if there are any redundant words in string or not .Is there any function that can provide me result in true/false.

Example:

 $str = "Hey! How are you";
 $result = redundant($str);
 echo $result ; //result should be 0 or false

But for :

 $str = "Hey! How are are you";
 $result = redundant($str);
 echo $result ; //result should be 1 or true

Thank you

  • http://stackoverflow.com/questions/14035945/finding-repeated-words-in-php-without-specifying-the-word-itself – Matt Feb 21 '16 at 14:55
  • @mkaatman : That is completely different thing.... Here, I just need true/false return . Not which word is repeating. Hope u understand. – Nahid Hossain Feb 21 '16 at 15:01
  • If any word has a count > 1, return true – Matt Feb 21 '16 at 15:13
  • 1
    A repeated word may not be "redundant." e.g. How did you know **that that** was what I was reading? ;-) – BryanT Feb 21 '16 at 15:16

2 Answers2

1

You could use explode to generate an array containing all words in your string:

$array = explode(" ", $str);

Than you could prove if the arrays contains duplicates with the function provided in this answer: https://stackoverflow.com/a/3145660/5420511

Community
  • 1
  • 1
deflox
  • 103
  • 2
  • 8
0

I think this is what you are trying to do, this splits on punctuation marks or whitespaces. The commented out lines can be used if you want the duplicated words:

$str = "Hey! How are are you?";
$output = redundant($str); 
echo $output;
function redundant($string){
    $words = preg_split('/[[:punct:]\s]+/', $string);
    if(max(array_count_values($words)) > 1) {
        return 1;
    } else {
        return 0;
    }
    //foreach(array_count_values($words) as $word => $count) {
    //  if($count > 1) {
    //      echo '"' . $word . '" is in the string more than once';
    //  }
    //}
}

References:
http://php.net/manual/en/function.array-count-values.php
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.preg-split.php

Regex Demo: https://regex101.com/r/iH0eA6/1

chris85
  • 23,846
  • 7
  • 34
  • 51