PHP正则表达式生成器 [英] PHP regex generator
问题描述
我现在有一个可以满足以下条件的正则表达式字符串:
I have now got a working regex string for the below needed criteria:
一行php就绪的正则表达式,包含许多关键字和关键词,并将至少与它们之一匹配.
a one line php-ready regex that encompasses a number of keywords, and keyterms and will match at least one of them.
例如:
关键字:
-
apple
-
banana
-
strawberry
-
pear cake
apple
banana
strawberry
pear cake
现在,如果找到这些关键术语中的任何一项,它将返回true.但是,要在这里增加一点难度,应将pear cake
术语拆分为两个关键字,它们必须都在字符串中,但不必在一起.
Now if any of these key terms are found then it returns true. However, to add a little more difficulty here, the pear cake
term should be split as two keywords which must both be in the string, but need not be together.
应返回true的示例字符串:
Example strings which should return 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
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函数,该函数将通过一系列关键术语即时创建此正则表达式.棘手的是,一个键术语在该键内可以有任意数量的关键字.仅需要找到一个关键术语,但是可以存在多个.如上所述,关键字词中的所有单词必须以任意顺序出现在字符串中.
Now I need a php function that will create this regex on the fly from an array of keyterms. The stickler is that a keyterm may have any number of keywords within that key. Only on of the keyterms need be found, but multiple can be present. As above all of the the words within a keyterm must appear in the string in any order.
推荐答案
我在这里为您编写了一个函数:
I have written a function for you here:
<?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')));
?>
我从以下位置获得了排列功能:
I got the permutations function from:
http://www.hashbangcode.com/blog/getting-all-permutations-array-php-74.html
但是我建议找到一个更好的函数并使用另一个函数,因为乍一看,这个函数很难看,因为无论如何它都会使$ i递增到10,000.
But I would recommend to find a better function and use another one since just at first glance this one is pretty ugly since it increments $i to 10,000 no matter what.
此外,这是代码的键盘:
Also, here is a codepad for the code:
让我知道它是否有问题!
Let me know if there is something wrong with it!
这篇关于PHP正则表达式生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!