0

我目前正在尝试使用 1000 个关键字每秒搜索多个字符串。直到最近,使用一些我可以发布的正则表达式一切都很好,但可能非常糟糕。我可以使用哪些方法?我读过一些关于 trie's 的文章,但不确定这些是否适合我的需要?

// 100 strings per second
// 100 characters long average
foreach ($stringSet as $haystack) {
    // 10000 keywords
    // 10 characters long average and can be multiple words
    $matches = stringContains($needles, $haystack)
    // Do stuff with matches
}

正则表达式(不太适合以前的代码,因为那是一种伪):

function stringContains($needles, $haystack) {
    $matchingTerms = array();
    $matches = array();
    foreach ($needles as $needle) {
        $needle = preg_split('/([^[:alnum:]])+/u',$needle);
        $needle = implode('',$needle);
        $needle  = preg_split('/(?<!^)(?!$)/u', $needle);
        $pattern = implode('[^[:alnum:]]*', $needle);
        $pattern = '/\b'.$pattern.'\b/iu';

        preg_match_all($pattern, $haystack, $matches);
        foreach ($matches as $match) {
            $matchingTerms = array_merge($matchingTerms, $match);
        }
    }
    return $matchingTerms;
}
4

1 回答 1

1

可能类似于以下内容。

function stringContains($needles, $haystack) {    
   $matchingTerms = array();
   $matches = array();

   foreach ($needles as $needle) {
      $pattern = "/\b(" . implode('|', $needle) . ")\b/i";
      $found   = preg_match_all($pattern, $haystack, $matches);

      if ($found) {
        $keys = array_unique($matches[0]);
        foreach ($keys as $key) {
           $matchingTerms = array_merge($matchingTerms, $key);
        }
      }
}
于 2013-09-15T00:11:48.963 回答