Laravel 5.5 - Check if string contains exact words

Viewed 30632

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?

4 Answers

Docs: https://laravel.com/docs/5.5/helpers#method-str-contains

The str_contains function determines if the given string contains the given value:

$contains = str_contains('This is my name', 'my');

You may also pass an array of values to determine if the given string contains any of the values:

$contains = str_contains('This is my name', ['my', 'foo']);
$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);
  }

}

Laravel Str::contains() method can check values against a work. Don't forget to use Illuminate\Support\Str;

Works on Laravel 7.x

Also accepts arrays of value. Instance:

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

if(Str::contains($string, $blacklistArray)){return true;}

// returns true

May not be your exact request though

str_contains() works with strings - not with arrays, but you can loop it:

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

$flag = false;
foreach ($blacklistArray as $k => $v) {
    if str_contains($string, $v) {
        $flag = true;
        break;
    }
}

if ($flag == true) {
    // someone was nasty
}
Related