我有badword函数,这个函数工作:像这样
<form action="bad.php" method="post" />
<br />
<br />
Your Word
<input type="text" placeholder="Your Word" name="in" />
<br />
<br />
<textarea name="bad" cols="20" rows="10">sex</textarea> *) parse by enter
<br />
<br />
<input type="submit" value="cek" name="cek" />
</form>
<?php
if(isset($_POST['cek'])){
function badWordFilter($data)
{
$bad= preg_split('/\r\n|[\r\n]/', $_POST['bad']);
$originals = (array_filter($bad));
$replacements = "";
$data = str_ireplace($originals,$replacements,$data);
return $data;
}
echo "<br />";
echo "Input : ".$_POST['in'];
echo "<br />";
echo "OutPut : ".badWordFilter($_POST['in']);
}
?>
输出显示:
in:foto sex with sexygirl
out:与女孩合影
但我想要输出 :
in:foto sex with sexygirl
out:与sexygirl合影
badword只删除留下的单词?
答案 0 :(得分:2)
请尝试以下代码:
function wordFilter($text)
{
$filter_terms = array('\bass(es|holes?)?\b', '\bshit(e|ted|ting|ty|head)\b');
$filtered_text = $text;
foreach($filter_terms as $word)
{
$match_count = preg_match_all('/' . $word . '/i', $text, $matches);
for($i = 0; $i < $match_count; $i++)
{
$bwstr = trim($matches[0][$i]);
$filtered_text = preg_replace('/\b' . $bwstr . '\b/', str_repeat("*", strlen($bwstr)), $filtered_text);
}
}
return $filtered_text;
}
您可以轻松地在$filter_terms
数组中添加单词;请注意,开始/和尾随/ i自动包含在循环中,无需每次都键入它们。你也可以添加“贪婪”的比赛;只需从单词的两端删除\ b,过滤器就会捕获包含该单词的任何内容。一个好主意是将所有术语从外部文件加载到数组中。
答案 1 :(得分:0)
以下代码完成了这项工作:
function badWordFilter($data)
{
$bad = preg_split('/\r\n|[\r\n]/', $_POST['bad']);
$originals = array_map('strtolower', array_filter($bad));;
$words = array_map('trim', explode(' ', $data));
$filtered = array_filter($words, function($v) use ($originals) {
return !in_array(strtolower($v), $originals);
});
return implode(' ', $filtered);
}
它将字符串拆分为单词,过滤掉坏字并构建新的过滤字符串。