此函数从文本中提交电子邮件并返回匹配的模式
function parse($text, $words)
{
$resultSet = array();
foreach ($words as $word){
$pattern = 'regex to match emails';
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE );
$this->pushToResultSet($matches);
}
return $resultSet;
}
类似地,我希望匹配文本中的错误单词并将其作为$resultSet
返回。
以下是过滤坏词的代码
$badwords = array('shit', 'fuck'); // Here we can use all bad words from database
$text = 'Man, I shot this f*ck, sh/t! fucking fu*ker sh!t f*cking sh\t ;)';
echo "filtered words <br>";
echo $text."<br/>";
$words = explode(' ', $text);
foreach ($words as $word)
{
$bad= false;
foreach ($badwords as $badword)
{
if (strlen($word) >= strlen($badword))
{
$wordOk = false;
for ($i = 0; $i < strlen($badword); $i++)
{
if ($badword[$i] !== $word[$i] && ctype_alpha($word[$i]))
{
$wordOk = true;
break;
}
}
if (!$wordOk)
{
$bad= true;
break;
}
}
}
echo $bad ? 'beep ' : ($word . ' '); // Here $bad words can be returned and replace with *.
}
用beep
但是我希望将匹配的错误字词推送到$this->pushToResultSet()
,并按照电子邮件过滤的第一个代码返回。
我可以使用错误的过滤代码执行此操作吗?
答案 0 :(得分:1)
大致转换David Atchley对PHP的回答,这是否按照您的意愿运行?
$blocked = array('fuck','shit','damn','hell','ass');
$text = 'Man, I shot this f*ck, damn sh/t! fucking fu*ker sh!t f*cking sh\t ;)';
$matched = preg_match_all("/(".implode('|', $blocked).")/i", $text, $matches);
$filter = preg_replace("/(".implode('|', $blocked).")/i", 'beep', $text);
var_dump($filter);
var_dump($matches);
答案 1 :(得分:0)
JSFiddle用于工作示例。
是的,您可以匹配坏词(保存以供日后使用),在文本中替换它们并根据您尝试过滤的错误单词数组动态构建正则表达式(您可以将其存储在数据库中,从JSON加载等)。以下是工作示例的主要部分:
var blocked = ['fuck','shit','damn','hell','ass'],
matchBlocked = new RegExp("("+blocked.join('|')+")", 'gi'),
text = $('.unfiltered').text(),
matched = text.match(matchBlocked),
filtered = text.replace(matchBlocked, 'beep');
请参阅上面的JSFiddle链接以获取完整的工作示例。