Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why having both str_replace() and preg_replace()?

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?

like image 506
Matteo Riva Avatar asked Sep 13 '26 16:09

Matteo Riva


2 Answers

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.

like image 65
Alan Storm Avatar answered Sep 16 '26 06:09

Alan Storm


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.

like image 39
Michael Borgwardt Avatar answered Sep 16 '26 08:09

Michael Borgwardt