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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47255135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:57:44  来源:igfitidea点击:

Laravel 5.5 - Check if string contains exact words

phplaravellaravel-5laravel-5.5

提问by Wonka

In laravel, I have a $stringand a $blacklistArray

在laravel中,我有一个$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

The result of $containsis 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

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

Cassandra

Ç屁股安德拉

However, this is a partial match and Cassandrais 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.

然而,这是一个部分匹配,Cassandra不是一个坏词,所以它不应该被标记。仅当字符串中的单词完全匹配时,才应对其进行标记。

Any idea how to accomplish this?

知道如何做到这一点吗?

采纳答案by Diego Cespedes

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

}

回答by set0x

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

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

The str_containsfunction determines if the given string contains the given value:

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

$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']);

回答by Tpojka

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

str_contains()适用于字符串 - 不适用于数组,但您可以循环它:

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