听起来您的问题的第 1 部分已经解决,因此此答案仅关注第 2 部分。据我了解,您正在尝试确定给定的输入消息是否包含任何顺序的所有单词列表。
这可以通过正则表达式和preg_match
每条消息的单个来完成,但是如果您有大量单词列表,则效率非常低。如果 N 是您要搜索的单词数,M 是消息的长度,那么算法应该是 O(N*M)。如果您注意到,每个关键字的正则表达式中有两个 .*
术语。使用前瞻断言,正则表达式引擎必须为每个关键字遍历一次。这是示例代码:
<?php
// sample messages
$msg1 = "Lose all the weight all the weight you want. It's fast and easy!";
$msg2 = 'Are you over weight? lose the pounds fast!';
$msg3 = 'Lose weight slowly by working really hard!';
// spam defining keywords (all required, but any order).
$keywords = array('lose', 'weight', 'fast');
//build the regex pattern using the array of keywords
$patt = '/(?=.*\b'. implode($keywords, '\b.*)(?=.*\b') . '\b.*)/is';
echo "The pattern is: '" .$patt. "'\n";
echo 'msg1 '. (preg_match($patt, $msg1) ? 'is' : 'is not') ." spam\n";
echo 'msg2 '. (preg_match($patt, $msg2) ? 'is' : 'is not') ." spam\n";
echo 'msg3 '. (preg_match($patt, $msg3) ? 'is' : 'is not') ." spam\n";
?>
输出是:
The pattern is: '/(?=.*\blose\b.*)(?=.*\bweight\b.*)(?=.*\bfast\b.*)/is'
msg1 is spam
msg2 is spam
msg3 is not spam
第二种解决方案似乎更复杂,因为代码更多,但正则表达式要简单得多。它没有前瞻断言,也没有.*
条款。该preg_match
函数在while
循环中被调用,但这并不是什么大问题。每条消息只遍历一次,复杂度应该是 O(M)。这也可以使用单个preg_match_all
函数来完成,但是您必须执行 anarray_search
才能获得最终计数。
<?php
// sample messages
$msg1 = "Lose all the weight all the weight you want. It's fast and easy!";
$msg2 = 'Are you over weight? lose the pounds fast!';
$msg3 = 'Lose weight slowly by working really hard!';
// spam defining keywords (all required, but any order).
$keywords = array('lose', 'weight', 'fast');
//build the regex pattern using the array of keywords
$patt = '/(\b'. implode($keywords,'\b|\b') .'\b)/is';
echo "The pattern is: '" .$patt. "'\n";
echo 'msg1 '. (matchall($patt, $msg1, $keywords) ? 'is' : 'is not') ." spam\n";
echo 'msg2 '. (matchall($patt, $msg2, $keywords) ? 'is' : 'is not') ." spam\n";
echo 'msg3 '. (matchall($patt, $msg3, $keywords) ? 'is' : 'is not') ." spam\n";
function matchall($patt, $msg, $keywords)
{
$offset = 0;
$matches = array();
$index = array_fill_keys($keywords, 0);
while( preg_match($patt, $msg, &$matches, PREG_OFFSET_CAPTURE, $offset) ) {
$offset = $matches[1][1] + strlen($matches[1][0]);
$index[strtolower($matches[1][0])] += 1;
}
return min($index);
}
?>
输出是:
The pattern is: '/(\blose\b|\bweight\b|\bfast\b)/is'
msg1 is spam
msg2 is spam
msg3 is not spam