Php 正则表达式关键字建议
我有以下数据集:Php 正则表达式关键字建议,php,regex,Php,Regex,我有以下数据集: names = ["brad pitt", "george clooney", "james cameron"]; 我需要一个与“布拉德·皮特”和“乔治·克鲁尼”匹配的正则表达式: 此外,它还应该匹配:“brad pitt”当查询为时,“brad peter pitt” 请注意,我使用的是PHP,我可以拆分查询并对其进行操作。例如,我可以尝试以下方法: ((brad)+.*(peter)+.*(pitt)+.*+) 但它不会匹配,因为每个名称后面有1个或多个,如果它放*(0
names = ["brad pitt", "george clooney", "james cameron"];
我需要一个与“布拉德·皮特”和“乔治·克鲁尼”匹配的正则表达式:
此外,它还应该匹配:“brad pitt”
当查询为时,“brad peter pitt”
请注意,我使用的是PHP,我可以拆分查询并对其进行操作。例如,我可以尝试以下方法:
((brad)+.*(peter)+.*(pitt)+.*+)
但它不会匹配,因为每个名称后面有1个或多个,如果它放*(0或更多),它会匹配所有记录,因为它也意味着不匹配任何内容。因此,如果字符串中有任何单词,您希望匹配该字符串。 为此,您可以在
\s+
上拆分字符串,并在表达式中使用每个单词,如:
word1|word2|word3
您可能还想添加一些\b
和/i
,例如(/
这次引用):
或者您可以使用三个单独的表达式或
indexOf()
检查。好,这里有一个简单的想法:
$arr = array("brad pitt", "george clooney", "james cameron");
$str = "brad peter clooney";
foreach($arr as $val)
{
$tmpptrn = str_replace(" ", "|", $val);
$pattern = "/($tmpptrn)/i";
if(preg_match_all($pattern, $str, $matches))
{
//do whatever with the results
$match = $matches[1][0];
if(!empty($match))
{
$arra[] = array_filter($arr, function($el) use ($match) { return ( strpos($el, $match) !== false ); });
}
}
}
//print out the results
print_r($arra);
布拉德·彼得·克鲁尼通过什么方式与布拉德·皮特和乔治·克鲁尼配对?我觉得这有点不清楚。基本问题是“如何检查给定字符串是否包含一组字符串中的一个”?这是一个关键字建议服务,如果您键入:brad peter clooney,系统应该能够建议两个名称。我可以用“/(*brad.*)|(*peter.*)|(*clooney.*)I/”这三个词中的任何一个,但这将匹配许多其他项目。例如,如果你搜索布拉德·皮特。它还将带来“brad james”对于这样的搜索,为了清晰起见,我建议对每个字符串中的单词使用迭代方法,而不是正则表达式。我认为这种方法的执行速度也会比运行一个包含大量或分隔符的正则表达式快,但这需要测试。这和:“/(*brad.*))|(*peter.*)|(*clooney.*)I/”不一样吗?在这种情况下,它会分解关键字,所以在搜索“brad pitt”时也会出现“brad james”
/\b(?:word1|word2|word3)\b/i
$arr = array("brad pitt", "george clooney", "james cameron");
$str = "brad peter clooney";
foreach($arr as $val)
{
$tmpptrn = str_replace(" ", "|", $val);
$pattern = "/($tmpptrn)/i";
if(preg_match_all($pattern, $str, $matches))
{
//do whatever with the results
$match = $matches[1][0];
if(!empty($match))
{
$arra[] = array_filter($arr, function($el) use ($match) { return ( strpos($el, $match) !== false ); });
}
}
}
//print out the results
print_r($arra);