如何在php中对字符串执行preg_replace


how to do a preg_replace on a string in php?

我有一些简单的代码可以进行preg匹配:

$bad_words = array('dic', 'tit', 'fuc',); //for this example i replaced the bad words
for($i = 0; $i < sizeof($bad_words); $i++)
{
    if(preg_match("/$bad_words[$i]/", $str, $matches))
    {
        $rep = str_pad('', strlen($bad_words[$i]), '*');
        $str = str_replace($bad_words[$i], $rep, $str);
    }
}
echo $str;

因此,如果$str"dic",结果将是"*",依此类推

现在,如果$str == f.u.c。解决方案可能是使用:

$pattern = '~f(.*)u(.*)c(.*)~i';
$replacement = '***';
$foo =  preg_replace($pattern, $replacement, $str);

在这种情况下,我将得到***,在任何情况下。我的问题是把所有这些代码放在一起。

我试过:

$pattern = '~f(.*)u(.*)c(.*)~i';
$replacement = 'fuc';
$fuc =  preg_replace($pattern, $replacement, $str);
$bad_words = array('dic', 'tit', $fuc,); 
for($i = 0; $i < sizeof($bad_words); $i++)
{
    if(preg_match("/$bad_words[$i]/", $str, $matches))
    {
        $rep = str_pad('', strlen($bad_words[$i]), '*');
            $str = str_replace($bad_words[$i], $rep, $str);
    }
}
echo $str;

这个想法是$fuc变成fuc,然后我把它放在数组中,然后数组完成它的工作,但这似乎不起作用。

首先,您可以用一个(动态生成的)正则表达式来替换所有坏词,如下所示:

$bad_words = array('dic', 'tit', 'fuc',);
$str = preg_replace_callback("/'b(?:" . implode( '|', $bad_words) . ")'b/", 
    function( $match) {
        return str_repeat( '*', strlen( $match[0])); 
}, $str);

现在,您遇到了人们在单词之间添加句点的问题,您可以用另一个正则表达式搜索并替换它们。但是,您必须记住,.与正则表达式中的任何字符匹配,并且必须转义(使用preg_quote()或反斜杠)。

$bad_words = array_map( function( $el) { 
    return implode( ''.', str_split( $el));
}, $bad_words);

这将创建一个类似于的$bad_words阵列

array(
    'd'.i'.c',
    't'.i'.t',
    'f'.u'.c'
)

现在,您可以像上面一样使用这个新的$bad_words数组来替换这些模糊的数组。

提示:您可以让这个array_map()调用"更好",因为它可以更智能地捕获更多的混淆。例如,如果你想捕捉一个用句点、空白字符或逗号分隔的坏单词,你可以这样做:

$bad_words = array_map( function( $el) { 
    return implode( '(?:'.|'s|,)', str_split( $el));
}, $bad_words);

现在,如果你让这个模糊组成为可选的,你会发现更多的脏话:

$bad_words = array_map( function( $el) { 
    return implode( '(?:'.|'s|,)?', str_split( $el));
}, $bad_words);

现在,坏词应该匹配:

f.u.c
f,u.c
f u c 
fu c
f.uc

还有更多。