我现在有一个正常工作的正则表达式字符串,用于以下所需的标准:
一行php-ready正则表达式,包含许多关键字和关键字,并且至少会匹配其中一个。
例如:
Keyterms:
apple
banana
strawberry
pear cake
现在,如果找到任何这些关键术语,则返回true。但是,要在此处添加更多难度,pear cake
术语应分为两个关键字,这两个关键字必须都在字符串中,但不必在一起。
应该返回true的示例字符串:
A great cake is made from pear
i like apples
i like apples and bananas
i like cakes made from pear and apples
I like cakes made from pears
工作正则表达式是:
/\bapple|\bbanana|\bstrawberry|\bpear.*?\bcake|\bcake.*?\bpear/
现在我需要一个php函数,它将从一组keyterms中动态创建这个正则表达式。关键词是关键词可以在该键中具有任意数量的关键词。只需要找到关键字,但可以存在多个关键字。如上所述,keyterm中的所有单词必须以任何顺序出现在字符串中。
答案 0 :(得分:0)
我在这里为你写了一个函数:
<?php
function permutations($array)
{
$list = array();
for ($i=0; $i<=10000; $i++) {
shuffle($array);
$tmp = implode(',',$array);
if (isset($list[$tmp])) {
$list[$tmp]++;
} else {
$list[$tmp] = 1;
}
}
ksort($list);
$list = array_keys($list);
return $list;
}
function CreateRegex($array)
{
$toReturn = '/';
foreach($array AS $value)
{
//Contains spaces
if(strpos($value, " ") != false)
{
$pieces = explode(" ", $value);
$combos = permutations($pieces);
foreach($combos AS $currentCombo)
{
$currentPieces = explode(',', $currentCombo);
foreach($currentPieces AS $finallyGotIt)
{
$toReturn .= '\b' . $finallyGotIt . '.*?';
}
$toReturn = substr($toReturn, 0, -3) . '|';
}
}
else
{
$toReturn .= '\b' . $value . '|';
}
}
$toReturn = substr($toReturn, 0, -1) . '/';
return $toReturn;
}
var_dump(CreateRegex(array('apple', 'banana', 'strawberry', 'pear cake')));
?>
我从下面得到了排列函数:
http://www.hashbangcode.com/blog/getting-all-permutations-array-php-74.html
但我建议找一个更好的功能并使用另一个,因为乍一看这个很难看,因为无论如何它都会将$ i增加到10,000。
此外,这是代码的键盘:
让我知道它是否有问题!