Laravel 5.5-检查字符串是否包含准确的单词

Won*_*nka 4 php laravel laravel-5 laravel-5.5

在拉拉韦尔,我有一个$string和一个$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
Run Code Online (Sandbox Code Playgroud)

结果$contains为true,因此将其标记为包含黑名单字(不正确)。这是因为下面的名称部分包含ass

Ç 屁股安德拉

但是,这是部分匹配,Cassandra并且不是一个坏词,因此不应对其进行标记。仅当字符串中的单词完全匹配时,才应对其进行标记。

任何想法如何做到这一点?

小智 8

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

str_contains函数确定给定的字符串是否包含给定的值:

$contains = str_contains('This is my name', 'my');
Run Code Online (Sandbox Code Playgroud)

您还可以传递一个值数组来确定给定的字符串是否包含任何值:

$contains = str_contains('This is my name', ['my', 'foo']);
Run Code Online (Sandbox Code Playgroud)


Die*_*des 5

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

}
Run Code Online (Sandbox Code Playgroud)