Search code examples
phpresourcespreg-matchstrpos

strpos vs preg_match - memory and resource differences


There have been questions asking which is faster strpos or preg_match, but I'm interested in knowing which uses the least memory and CPU resources.

I want to check a line for one of 5 matches:

if (strpos($key, 'matchA') !== false || strpos($key, 'matchB') !== false || strpos($key, 'matchC') !== false || strpos($key, 'matchD') !== false || strpos($key, 'matchE') !== false) 

if (preg_match("~(matchA|matchB|matchC|matchD|matchE)~i",$key, $match))

What is the best way to do this using the least strain on the server?


Solution

  • Jeffrey Friedl's Mastering Regular Expressions said that using the built in non-regex functions like strpos() and str_match() is always better and faster than using preg_match() (assuming you're using the preg suite) given that your match text is not a pattern.