首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >最快的PHP例程来匹配单词

最快的PHP例程来匹配单词
EN

Stack Overflow用户
提问于 2010-04-13 20:25:49
回答 6查看 3K关注 0票数 5

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

例如,如果我的关键词短语是"great皮革鞋“,那么以下标题将是匹配的.

  • 买一些真正的大皮鞋
  • 皮鞋
  • 伟大的日!这是一些酷皮鞋
  • Shoes,由皮革制成,可以是

...while --它们将不是匹配的:

  • 皮鞋在今天的销售!
  • 你会非常喜欢这双皮鞋的
  • 大鞋不便宜

我想,用数组函数或RegEx (正则表达式)来快速实现这一点是有一些技巧的。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-04-13 22:21:53

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

代码语言:javascript
复制
$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";
}
票数 4
EN

Stack Overflow用户

发布于 2010-04-13 20:55:17

您可以对类似的东西进行preg_grep()数组

代码语言:javascript
复制
 /^(?=.*?\bgreat)(?=.*?\bleather)(?=.*?\shoes)/

或者(可能更快) grep每个单词分开,然后array_intersect结果

票数 3
EN

Stack Overflow用户

发布于 2010-04-13 21:03:41

这可能是一个相当天真的解决方案(很可能有更高效/优雅的解决方案),但我可能会这样做:

代码语言:javascript
复制
$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 );

不过,我不知道这是怎么回事。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2632951

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档