I came to know PHP after Perl, so when I first found preg_* function I basically just used those. Later I read that str_replace() is faster when dealing with literal text. So my question is, can’t preg_replace() be as efficient as str_replace() when the search pattern does not use special characters? Maybe just analyzing the pattern to choose between regex and plain text algorithms?
I came to know PHP after Perl, so when I first found preg_* function
Share
In theory yes, you’re right. It is possible the PHP team could jigger
preg_replaceto analyze the pattern being passed in and then use the code forstr_replaceif it didn’t see any meta-characters. Assuming the analysis wasn’t too heavy, this might yield better performance results.However, the way the PHP source code (that is, the code used to implement PHP) is organized doesn’t lend itself well to this sharing. PHP is (in some ways) less a full language and more a collection of modules.
So, initially the PHP group chose to stay away from this kind of cross module pollination. At this point, changing the
preg_replacefunction to do that kind of analysis would risk breaking a lot of code, and the performance improvements would be minuscule.Finally, the analysis itself is a harder problem to solve than you’d think. Tell me, does this pattern
mean I should search for the literal text
or the literal text
It’s easy to come up with compelling arguments for either interpretation, which introduces an additional level of confusion into using the function.
An interesting idea in theory, but in practice and the context of the PHP universe, it creates far more problems than it solves.