配列に単語のリストがあります。これらの単語のいずれかが文字列に存在するかどうかを確認する最速の方法は何ですか?
foreach
現在、ループ byを介して、配列要素の存在を 1 つずつ確認していますstripos
。str_replace
配列を使用する場合のように、より高速な方法があるかどうかに興味があります。
追加のコメントに関しては、explode() またはpreg_split()を使用して文字列を単一の単語に分解し、 array_intersect() を使用してこの配列をneedles -array に対してチェックできます。したがって、すべての作業は一度だけ行われます。
<?php
$haystack = "Hello Houston, we have a problem";
$haystacks = preg_split("/\b/", $haystack);
$needles = array("Chicago", "New York", "Houston");
$intersect = array_intersect($haystacks, $needles);
$count = count($intersect);
var_dump($count, $intersect);
array_intersect() はかなり高速だと想像できます。しかし、それはあなたが本当に欲しいものに依存します(一致する単語、一致するフラグメント、..)
私の個人的な機能:
function wordsFound($haystack,$needles) {
return preg_match('/\b('.implode('|',$needles).')\b/i',$haystack);
}
//> Usage:
if (wordsFound('string string string',array('words')))
UTF-8 のエキゾチックな文字列を使用する場合は、\b を utf-8 preg の単語境界に対応するものに変更する必要があることに注意してください。
preg_quote
Notice2: $needles には必ず a-z0-9 文字のみを入力してください (MonkeyMonkey のおかげです)。
i
Notice3: この関数は修飾子のおかげで大文字と小文字を区別しません
一般に、正規表現は のような基本的な文字列関数に比べて遅くなりますstr_ipos()
。でも本当に状況によると思います。最大限のパフォーマンスが本当に必要な場合は、実際のデータを使用していくつかのテストを行うことをお勧めします。