繁体   English   中英

在PHP中,将字符串与关键字列表进行匹配的最有效方法是什么?

[英]In PHP, what is the most efficient way to match a string against a list of keywords?

我有一个关键字列表,需要检查是否其中任何一个出现在字符串中。 例如:

/* Keywords */
Rock
Paper
Scissors

/* Strings */
"This town rocks!"    /* Match */
"Paper is patient"    /* Match */
"Hello, world!"       /* No match */

我可以将关键字放入数组中,循环遍历并在每次迭代中执行preg_match()或substr(),但这似乎有点cpu昂贵。 我已经用正则表达式搞糊涂了,但是没有成功。

什么是最有效的方法(就精简代码和低CPU负载而言)?

请注意,比较必须不区分大小写。

具有所有替代项的正则表达式将确保对字符串进行一次扫描,而不是对N个关键字进行N次扫描。 PCRE库已非常优化。

preg_match('/rock|paper|scissors/i', $string);

如果您的关键字具有通用前缀并且您可以利用它(基本上通过构建特里并内联它),它将变得更快:

preg_match('/rock|paper|sci(?:ssors|ence)/i', $string);

最后是

preg_grep($regex, $array_of_strings);

将与字符串数组匹配并返回匹配的字符串。

只是为了查看是否找到任何关键字,您可以使用关键字作为数组来做到这一点:

if(str_ireplace($keyword_array, '', $string) != $string) {
    //match
} else {
    //no match
}

如果您事先不知道关键字,并且希望搜索多个字符串,则可以将关键字内嵌到正则表达式并grep字符串:

$keywords = array ('Rock', 'Paper', 'sciSSors');
$strings  = array (
    "This town rocks!",
    "Hello, world!",
    "Paper is patient",
);

$rc = preg_grep(
    sprintf('/%s/i', implode('|', array_map('preg_quote', $keywords))),
    $strings
);

/**
array(2) {
  [0]=>
  string(16) "This town rocks!"
  [2]=>
  string(16) "Paper is patient"
}
*/

在这里看到它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM