簡體   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