在 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
的结果为true,因此这将被标记为包含黑名单单词(这是不正确的)。这是因为下面的名称部分包含ass
C屁股安德拉
但是,这是部分匹配,并且
Cassandra
并不是一个坏词,因此不应标记它。仅当字符串中的单词完全匹配时,才应对其进行标记。
知道如何实现这一点吗?
文档: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']);
$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()
方法可以根据工作检查值。别忘了use Illuminate\Support\Str;
适用于 Laravel 7.x
也接受值数组。实例:
$string = 'Cassandra 是一个干净的词,所以它应该通过检查'; $blacklistArray = ['屁股','球袋'];
if(Str::contains($string, $blacklistArray)){return true;}
// returns true
但可能不是您的确切要求
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
}
str_contains($body, $search) - 用于在字符串中查找字符串。
Illuminate\Support\Str::contains($body, $search) - 与 PHP 完全相同 str_contains(),但它也支持数组值“$search”
但这两种情况都是部分搜索,这意味着
str_contains('consent', 'sent') //true
Illuminate\Support\Str::contains('consent', 'sent') //true
如果我们使用正则表达式,我们就可以实现这一点。以下是我在项目中使用的功能:
function is_word_contains($needle,$haystack,$i,$word) {
// $i should be "" or "i" for case insensitive
if (strtoupper($word)=="W")
{ // if $word is "W" then word search instead of string in string search.
// echo "/\b{$needle}\b/{$i}";
if (preg_match("/\b{$needle}\b/{$i}", $haystack))
{
return true;
}
}
else
{
if(preg_match("/{$needle}/{$i}", $haystack))
{
return true;
}
}
return false;
// Put quotes around true and false above to return them as strings instead of as bools/ints.
}