0

我想在 PHP 中创建一个函数,当它发现字符串中有一些坏词时将返回 true。

这是一个例子:

function stopWords($string, $stopwords) {
if(the words in the stopwords variable are found in the string) {
return true;
}else{
return false;
}

请假设$stopwords变量是一个值数组,例如:

$stopwords = array('fuc', 'dic', 'pus');

我怎样才能做到这一点?

谢谢

4

3 回答 3

1

使用strpos函数。

// the function assumes the $stopwords to be an array of strings that each represent a
//  word that should not be in $string
function stopWords($string, $stopwords) 
{  
     // input parameters validation excluded for brevity..

     // take each of the words in the $stopwords array
     foreach($stopwords as $badWord)
     {
         // if the $badWord is found in the $string the strpos will return non-FALSE        
         if(strpos($string, $badWord) !== FALSE))
           return TRUE;
     }
     // if the function hasn't returned TRUE yet it must be that no bad words were found
     return FALSE;
 }
于 2012-02-04T21:53:00.303 回答
1

使用正则表达式

  • \b匹配一个单词边界,用它来匹配整个单词
  • 使用标志i执行不区分大小写的匹配

像这样匹配每个单词:

function stopWords($string, $stopwords) {
    foreach ($stopwords as $stopword) {
        $pattern = '/\b' . $stopword . '\b/i';
        if (preg_match($pattern, $string)) {
            return true;
        }
    }
    return false;
}

$stopwords = array('fuc', 'dic', 'pus');

$bad = stopWords('confucius', $stopwords); // true
$bad = stopWords('what the Fuc?', $stopwords); // false

一个较短的版本,灵感来自对这个问题的回答:确定一个字符串是否包含数组中的一组单词中的一个,用于implode创建一个大表达式:

function stopWords($string, $stopwords) {
    $pattern = '/\b(' . implode('|', $stopwords) . ')\b/i';
    return preg_match($pattern, $string) > 0;
}
于 2012-02-04T22:03:39.850 回答
0
function stopWords($string, $stopwords) {
    $words=explode(' ', $string); //splits the string into words and stores it in an array
    foreach($stopwords as $stopword)//loops through the stop words array
    {
        if(in_array($stopword, $words)) {//if the current stop word exists 
            //in the words contained in $string then exit the function 
            //immediately and return true
            return true;
        }
    }
    //else if none of the stop words were in $string then return false
    return false;
}

我假设这$stopwords是一个开始的数组。如果不是,应该是。

于 2012-02-04T21:56:32.660 回答