Search code examples
phpregexperformancerequesthandler

Is using regex for a request handler in PHP bad?


I am working on a request handler to route every page call through my index page and have SEO friendly urls.

domain.com/account/settings

this would be easy to map to the correct page but some are more complex when there becomes an ID number or a page number in the uri.

So I see some people will use things like preg_match and cycle through an array of patterns -> uri to get a match which is nice for when paging and id's come into play but from my experience, it seems like running preg_match on an array of say 20 items on every page load is not good for performace.

Please tell me your thought on this?


Solution

  • A not-very-complex regex on a string as short as an URI will take very little time, even running 20 times through. If you have a) profiled or timed it to prove it's a performance problem, and b) a good alternative to use instead then you could try changing it around but otherwise I wouldn't worry to much about it. Tons of sites do something similar with mod_rewrite after all, checking the page URI against a series of regexes on every page load.

    If need be, you could probably reduce that 20 times to less for each URI with a few simple strstr() checks to see what basic format the URI is in (whether it contains a id or not, a page number or not, etc). Optimizing your regexes, such as using the "start" ^ and "end" $ meta-characters wherever possible, will help too.