ISSUE :
 
Profile photo
Submitted by Richard Cox
on June 15th, 2011 at 10:19:24 EST

Whether preg_replace() or str_replace() is good in performace?

I am using both preg_replace() and str_replace(). And this is more of performance question. I wanted to know which one is good in terms of peformance than the other? Is there is any preference on which one should be used?


Profile photo
Replied by Tim Joseph
on June 15th, 2011 at 14:24:39 EST
From what I see both of these php methods have different purpose. preg_replace() is based on regular expression replacement and other one str_replace() based on regular string replacement.

If you are doing something as simple as preg_replace("/^foo$/", "newFoo", "this is foo statement"); then it does not make sense to use preg_replace() method and could be easily fulfilled by str_replace(). But if you have to match complex pattern then there is no other choice than using preg_replace(). You can not do complex pattern replacement with str_replace() method.

My thumb rule is, if your requirement can be resolved using str_replace(), great use it ELSE go with preg_replace().
Remember, when you use preg_replace() there is of course some overhead of whole php regex engine. I normally avoid using regular expression if it can be resolved using other simple methods. I hope this helps.
Accepted Answer
Accepted
 Answer

Profile photo
Replied by Richard Cox
on June 15th, 2011 at 15:17:52 EST
Thanks for the explanation.