考虑以下数组元素
1.benclinton
2.clintonharry
3.harryben
4.benwill
5.jasonsmith
6.smithclinton
假设模式列表是ben,harry,clinton,那么我应该得到的结果是
1.benclinton
2.clintonharry
3.harryben
因此,基本上结果应该包含仅包含模式列表中的单词的字符串。订单并不重要
此外,每个字符串不会超过两个单词。即bensmith将永远不会是一个案例。
由于我的所有字符串都在一个数组中,我想在php中使用preg_grep来做到这一点,但是我为此构建了正确的正则表达式。
什么正则表达式可以实现这一点?除了可以完成工作的正则表达式匹配之外还有其他有效的方法吗?
提前致谢!
像这样的东西
$names_list = ['benclinton','clintonharry','harryben','benwill','jasonsmith','smithclinton'];
$names = ['ben','harry','clinton'];
$matches = preg_grep('/('.implode('|',$names).')(?1)/', $names_list);
//- /(ben|harry|clinton)(?1)/ -- (?1) = recurse capture group 1
print_r($matches);
产量
Array
(
[0] => benclinton
[1] => clintonharry
[2] => harryben
)
这要求至少两个名称(即使是相同的一个2x)匹配。但在这种情况下,这是一种给定的,或者一切都会匹配。
如果你想要格外小心,如果$names
可以包含对正则表达式重要的东西,比如+
,*
,\
等你可以添加这个
$matches = preg_grep('/('.implode('|',array_map(function($name){return preg_quote($name,'/');},$names)).')(?1)/', $names_list);
您似乎希望匹配两个关键字的精确组合的数组元素。对于正则表达式方法,我们可以尝试获取关键字向量的交叉乘积,然后生成交替。然后,我们可以对输入数组使用preg_grep
来查找所有匹配的元素。
$array = array("benclinton", "clintonharry", "harryben", "benwill", "jasonsmith", "smithclinton");
$input = array("ben", "harry", "clinton");
$regex = "";
foreach ($input as $term1) {
foreach ($input as $term2) {
if ($regex != "") $regex .= "|";
$regex .= $term1.$term2;
}
}
$regex = "/^(" . $regex . ")$/";
$matches = preg_grep($regex, $array);
print_r($matches);
Array
(
[0] => benclinton
[1] => clintonharry
[2] => harryben
)
以下是上述脚本生成的正则表达式替换:
(benben|benharry|benclinton|harryben|harryharry|harryclinton|clintonben|
clintonharry|clintonclinton)
没有Regex.Do与array_filter
和strpos
<?php
$a = ['benclinton','clintonharry','harryben','benwill','jasonsmith','smithclinton'];
$a2 = ['ben','clinton','harry'];
$res = array_filter($a,function($str="") use($a2){
$r =array_filter($a2,function($a2str) use($str){
return strpos($str,$a2str) !== FALSE;
});
return count($r) > 1;
});
print_r($res);
?>