用星星和输出数组替换php坏词

时间:2017-11-07 09:33:22

标签: php arrays regex

以下php函数用于替换带有启动的坏词,但我需要一个额外的参数来描述发现的坏词。

    $badwords = array('dog', 'dala', 'bad3', 'ass');
    $text = 'This is a dog. . Grass. is good but ass is bad.';
    print_r( filterBadwords($text,$badwords));


    function filterBadwords($text, array $badwords, $replaceChar = '*') {
$repu = preg_replace_callback(array_map(function($w) { return '/\b' . preg_quote($w, '/') . '\b/i'; }, $badwords),
        function($match) use ($replaceChar) {
                    return str_repeat($replaceChar, strlen($match[0])); },
                    $text

                    );
 return array('error' =>'Match/No Match', 'text' => $repu );   
}// Func

如果找到坏词,则输出

  

数组([错误] =>匹配[text] =>错误的狗匹配。)

如果没有找到坏词,那么

  

数组([错误] =>不匹配[text] =>错误字匹配。)

2 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

function filterBadwords($text, array $badwords, $replaceChar = '*') {
   //new bool var to see if there was any match
    $matched = false;
    $repu = preg_replace_callback(array_map(
        function($w)
        {
            return '/\b' . preg_quote($w, '/') . '\b/i'; 
        }, $badwords),
        //pass the $matched by reference
        function($match) use ($replaceChar, &$matched)
        {
            //if the $match array is not empty update $matched to true
            if(!empty($match))
            {
                $matched = true;
            }
            return str_repeat($replaceChar, strlen($match[0]));
        }, $text);
    //return response based on the bool value of $matched
    if($matched)
    {
        $return = array('error' =>'Match', 'text' => $repu );
    }
    else
    {
        $return = array('error' =>'No Match', 'text' => $repu );
    }
    return $return;   
}

这会使用referenceif条件查看是否存在任何匹配项,然后根据该条件返回响应。

输出(如果匹配):

array (size=2)
  'error' => string 'Match' (length=5)
  'text' => string 'This is a ***. . Grass. is good but *** is bad.'

输出(如果没有匹配):

array (size=2)
  'error' => string 'No Match' (length=8)
  'text' => string 'This is a . . Grass. is good but  is bad.'

答案 1 :(得分:0)

<?php
$badwords = array('dog', 'dala', 'bad3', 'ass');
$text = 'This is a dog. . Grass. is good but ass is bad.';
$res=is_badword($badwords,$text);
echo "<pre>"; print_r($res);


function is_badword($badwords, $text) 
{    
    $res=array('No Error','No Match');
    foreach ($badwords as $name) {
        if (stripos($text, $name) !== FALSE) {
            $res=array($name,'Match');
            return $res;
        }
    }
    return $res;
}

?>

Output: 

Array
(
    [0] => dog
    [1] => Match
)