在PHP中,获取关键字列表并将其与所有单词的搜索结果(如标题数组)匹配的最快方法是什么?
例如,如果我的关键词短语是"great皮革鞋“,那么以下标题将是匹配的.
...while --它们将不是匹配的:
我想,用数组函数或RegEx (正则表达式)来快速实现这一点是有一些技巧的。
发布于 2010-04-13 22:21:53
我会为标题中的单词使用索引,并测试是否每个搜索项都在该索引中:
$terms = explode(' ', 'great leather shoes');
$titles = array(
'Get Some Really Great Leather Shoes',
'Leather Shoes Are Great',
'Great Day! Those Are Some Cool Leather Shoes!',
'Shoes, Made of Leather, Can Be Great'
);
foreach ($titles as $title) {
// extract words in lowercase and use them as key for the word index
$wordIndex = array_flip(preg_split('/\P{L}+/u', mb_strtolower($title), -1, PREG_SPLIT_NO_EMPTY));
// look up if every search term is in the index
foreach ($terms as $term) {
if (!isset($wordIndex[$term])) {
// if one is missing, continue with the outer foreach
continue 2;
}
}
// echo matched title
echo "match: $title";
}发布于 2010-04-13 20:55:17
您可以对类似的东西进行preg_grep()数组
/^(?=.*?\bgreat)(?=.*?\bleather)(?=.*?\shoes)/或者(可能更快) grep每个单词分开,然后array_intersect结果
发布于 2010-04-13 21:03:41
这可能是一个相当天真的解决方案(很可能有更高效/优雅的解决方案),但我可能会这样做:
$keywords = array(
'great',
'leather',
'shoes'
);
$titles = array(
'Get Some Really Great Leather Shoes',
'Leather Shoes Are Great',
'Great Day! Those Are Some Cool Leather Shoes!',
'Shoes, Made of Leather, Can Be Great',
'Leather Shoes on Sale Today!',
'You\'ll Love These Leather Shoes Greatly',
'Great Shoes Don\'t Come Cheap'
);
$matches = array();
foreach( $titles as $title )
{
$wordsInTitle = preg_split( '~\b(\W+\b)?~', $title, null, PREG_SPLIT_NO_EMPTY );
if( array_uintersect( $keywords, $wordsInTitle, 'strcasecmp' ) == $keywords )
{
// we have a match
$matches[] = $title;
}
}
var_dump( $matches );不过,我不知道这是怎么回事。
https://stackoverflow.com/questions/2632951
复制相似问题