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

时间:2017-11-12 23:22:26

标签: php laravel laravel-5 laravel-5.5

在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

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

C 的Andra

但是,这是部分匹配,Cassandra不是坏词,因此不应标记。只有当字符串中的单词完全匹配时,才应标记它。

知道怎么做到这一点吗?

4 个答案:

答案 0 :(得分:6)

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

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

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

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

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

答案 1 :(得分:3)

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

}

答案 2 :(得分:1)

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
}

答案 3 :(得分:0)

Laravel @MapperConfig( componentModel = "spring", nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE ) public interface BaseMapperConfig { } 方法可以根据作品检查值。不要忘记@Mapper(config = BaseMapperConfig.class) public interface SomeObjectMapper { ... }

在Laravel 7.x上工作

也接受值数组。实例:

$ string ='Cassandra是一个干净的词,因此它应该通过检查” $ blacklistArray = ['ass','ball sack'];

Str::contains()

虽然可能不是您的确切要求