regex - In PHP, what is the most efficient way to match a string against a list of keywords? -


i have list of keywords, , need check whether of these occurs in string. e.g.:

/* keywords */ rock paper scissors  /* strings */ "this town rocks!"    /* match */ "paper patient"    /* match */ "hello, world!"       /* no match */ 

i put keywords in array, loop through , preg_match() or substr() on each iteration, seems bit cpu-expensive. i've mucked aroud regexps bit, without success.

what efficient way (in terms of lean code , low cpu loads) this?

note comparison must case-insensitive.

a regex alternatives ensure string scanned once, rather n times n keywords. pcre library optimized.

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

it gets faster if keywords have common prefixes , take advantage of (essentially building trie , inlining it):

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

and there's

preg_grep($regex, $array_of_strings); 

that match against array of strings , return ones match.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -