Why use str_replace () and preg_replace ()?

I met PHP after Perl, so when I first found the preg_ * function, I mostly used them. Later I read that it’s str_replace()faster when it comes to literal text. So my question is: can't it preg_replace()be as effective as str_replace()when when the search pattern doesn't use special characters? Maybe just analyze the pattern to choose between regular expressions and plain text algorithms?

+3
source share
8 answers

In theory, yes, you're right. Perhaps the PHP team can jigger preg_replaceparse the transmitted pattern, and then use the code for str_replaceif it does not see the metacharacters. Assuming the analysis is not too heavy, this one may provide better results.

However, the way to organize the PHP source code (i.e. the code used to implement PHP) is not suitable for this sharing. PHP (in some way) has less complete language and more set of modules.

So, initially the PHP team chose to stay away from this kind of cross-module experiment. At this stage, changing the function preg_replaceto perform such an analysis can lead to a violation of a large amount of code, and performance improvements will be minor.

, - , . ,

 '/123/'

,

123

/123/

, .

, PHP, , .

+7

, ?

, , .

+5

, / , str_ *. . , , :)

, .

0

, , . , preg_replace , :

preg_replace ('/(\w+) apple/', '$1 pear', 'A red apple'); // => 'A red pear'
0

javascript

alert("a.b".replace(".", "X")) // aXb
alert("a.b".replace(/./, "X")) // X.b

, . Regexp , ( split "explode" "preg_split", pos "strpos" "preg_match" ..).

, , , regexp php .

0

, ?

. , preg_*() , .

0

str_replace() preg_replace(), , . , , .

preg_replace(), , , . , , , ; , .

0

preg is good for complex text replacements (textual hyperlink to the actual link). the other is for changing words (for example, a word filter).

if you have spaces that can be matched by a pattern, use preg otherwise with str_replace.

although it tries to do the same in preg with str_replace, it is actually slower if you do complex things.

Joe

-1
source

Source: https://habr.com/ru/post/1725891/


All Articles