Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_replace/preg_match vs PHP str_replace

Can anyone give me a quick summary of the differences please?

To my mind they both do the same thing?

Thanks

like image 303
benhowdle89 Avatar asked Mar 09 '11 12:03

benhowdle89


People also ask

What is the difference between Str_replace and Preg_replace?

str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f. {2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.

What does Preg_replace do in PHP?

The preg_replace() function returns a string or array of strings where all matches of a pattern or list of patterns found in the input are replaced with substrings. There are three different ways to use this function: 1. One pattern and a replacement string.


2 Answers

str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f.{2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.

[EDIT]

See for yourself:

$string = "foo fighters"; $str_replace = str_replace('foo','bar',$string); $preg_replace = preg_replace('/f.{2}/','bar',$string); echo 'str_replace: ' . $str_replace . ', preg_replace: ' . $preg_replace; 

The output is:

str_replace: bar fighters, preg_replace: bar barhters

:)

like image 95
mingos Avatar answered Nov 07 '22 17:11

mingos


str_replace will just replace a fixed string with another fixed string, and it will be much faster.

The regular expression functions allow you to search for and replace with a non-fixed pattern called a regular expression. There are many "flavors" of regular expression which are mostly similar but have certain details differ; the one we are talking about here is Perl Compatible Regular Expressions (PCRE).

If they look the same to you, then you should use str_replace.

like image 38
Jon Avatar answered Nov 07 '22 17:11

Jon