最快的PHP例程来匹配单词

Vol*_*ike 5 php regex arrays keyword

PHP中获取关键字列表并将其与所有单词的搜索结果(如标题数组)匹配的最快方法是什么?

例如,如果我的关键词短语是" 精美皮鞋 ",那么以下标题就是匹配...

  • 得到一些真正伟大的皮鞋
  • 皮鞋
  • 美好的一天!那些是很酷的皮鞋!
  • 鞋子,皮革制成,可以很棒

......虽然这些匹配:

  • 今日特卖皮鞋!
  • 你会爱上这些皮鞋大大
  • 伟大的鞋子不便宜

我想有一些关于数组函数或RegEx(正则表达式)的技巧可以快速实现.

Gum*_*mbo 4

我会为标题中的单词使用索引,并测试每个搜索词是否都在该索引中:

$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";
}
Run Code Online (Sandbox Code Playgroud)