41

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

To my mind, are they both doing the same thing?

Muhammad Dyas Yaskur
  • 6,914
  • 10
  • 48
  • 73
benhowdle89
  • 36,900
  • 69
  • 202
  • 331

4 Answers4

54

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

:)

mingos
  • 23,778
  • 12
  • 70
  • 107
21

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • well it is nice for dynamic searches in patterns you dont know, but if you know the pattern (even if during runtime) you can create the button right then and do str_ unless you want different parts to be catched at the same time. – My1 Feb 25 '16 at 10:11
5

str_replace searches for pure text occurences while preg_replace for patterns.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Mārtiņš Briedis
  • 17,396
  • 5
  • 54
  • 76
2

I have not tested by myself, but probably worth of testing. But according to some sources preg_replace is 2x faster on PHP 7 and above.

See more here: preg_replace vs string_replace.

D.A.H
  • 858
  • 2
  • 9
  • 19