我有以下代码,我想用它作为脏话过滤器。
<?php
$replace = array(
'dog' => '***',
'apple' => '*****',
'chevy' => '*****'
);
$string = 'I like dog to eat an Apple with my Dog in my Chevy';
echo strReplaceAssoc($replace,$string);
function strReplaceAssoc(array $replace, $subject) {
return str_ireplace(array_keys($replace), array_values($replace), $subject);
}
// Result: I like *** to eat an ***** with my *** in my *****
?>
我需要对此进行调整,以创建一个替代结果,其中突出显示坏词(包含在强标签中)而不是加星标,我还需要保留用户输入的单词的原始大小。
所以我的结果会是这样的:
I like <strong>dog</strong> to eat as <strong>Apple</strong> with my <strong>Dog</strong> in my <strong>Chevy</strong>
是否有一种简单的方法可以调整我的代码来执行此操作?
修改!!!!!
这是迄今为止我提出的最佳解决方案:
$replace = array(
'dog',
'apple',
'chevy'
);
$string = 'I like dog to eat an Apple with my Dog in my Chevy Chevy chevy';
function filterwords($text, array $filterWords){
$filterCount = sizeof($filterWords);
for($i=0; $i<$filterCount; $i++){
$text = preg_replace('/\b'.$filterWords[$i].'\b/ie',"str_repeat('*',strlen('$0'))",$text);
}
return $text;
}
function strReplace($subject, array $blacklist) {
return array_reduce($blacklist, function ($r, $v) {
return $r = preg_replace('/('.preg_quote($v, '/').')/i', '<strong>$1</strong>', $r);
}, $subject);
}
echo filterwords($string, $replace);
echo '<br />';
echo strReplace($string, $replace);
答案 0 :(得分:1)
使用基于评论的新解决方案进行编辑:
function replaceWords($str, $star = true){
$replace = array(
"/(dog)/i",
"/(cat)/i"
);
if ($star){
$with = '***';
} else {
$with = '<strong>$1</strong>';
}
return preg_replace($replace, $with, $str);
}
echo replaceWords("I like dog and cat and duck.");
echo replaceWords("I like dog and cat and duck", false);
/* Results: I like *** and *** and duck.I like <strong>dog</strong> and <strong>cat</strong> and duck */
答案 1 :(得分:1)
您可以将array_reduce
与str_ireplace
结合使用。所以代码看起来像这样:
function strReplace(array $blacklist, $subject) {
return array_reduce($blacklist, function ($r, $v) {
return $r = str_ireplace($v, "<strong>$v</strong>", $r);
}, $subject);
}
$blacklist = array(
'dog',
'apple',
'chevy',
);
$string = 'I like dog to eat an Apple with my Dog in my Chevy';
$result = strReplace($blacklist, $string);
<强>更新强>
保留不良字词的 strReplace
版本&#39;情况下:
function strReplace(array $blacklist, $subject) {
return array_reduce($blacklist, function ($r, $v) {
return $r = preg_replace('/('.preg_quote($v, '/').')/i', '<strong>$1</strong>', $r);
}, $subject);
}