Search code examples
phplaravellaravel-5laravel-5.5

Laravel 5.5 - Check if string contains exact words


In laravel, I have a $string and a $blacklistArray

$string = 'Cassandra is a clean word so it should pass the check';
$blacklistArray = ['ass','ball sack'];

$contains = str_contains($string, $blacklistArray); // true, contains bad word

The result of $contains is true, so this will be flagged as containing a black list word (which is not correct). This is because the name below partially contains ass

Cassandra

However, this is a partial match and Cassandra is not a bad word, so it should not be flagged. Only if a word in the string is an exact match, should it be flagged.

Any idea how to accomplish this?


Solution

  • $blacklistArray = array('ass','ball sack');
    
    $string = 'Cassandra is a clean word so it should pass the check';
    
    
    
    $matches = array();
    $matchFound = preg_match_all(
                    "/\b(" . implode($blacklistArray,"|") . ")\b/i", 
                    $string, 
                    $matches
                  );
    
    // if it find matches bad words
    
    if ($matchFound) {
      $words = array_unique($matches[0]);
      foreach($words as $word) {
    
        //show bad words found
        dd($word);
      }
    
    }