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?
In theory yes, you're right. It is possible the PHP team could jigger preg_replace to analyze the pattern being passed in and then use the code for str_replace if 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_replace function 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
'/123/'
mean I should search for the literal text
123
or the literal text
/123/
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.
Maybe just analyzing the pattern to choose between regex and plain text algorithms?
I'd rather not be forced to escape everything that has special meaning in regular expressions every time I just want to replace some substrings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With