103

I got an error by this regular expression...

$strTmp = preg_replace('~(<\/CharacterStyleRange>(.*?)\n*</CharacterStyleRange>)~gim ' , "</CharacterStyleRange>", $strTmp);

Error

Warning: preg_replace(): Unknown modifier 'g' in ....

Why?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Foo Ling
  • 1,091
  • 2
  • 7
  • 8

3 Answers3

203

g is implicit with preg_replace(). You don't need to include it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rid
  • 61,078
  • 31
  • 152
  • 193
  • See [the other good answer](https://stackoverflow.com/a/19061066/114558) on this question for more background. – rinogo Nov 27 '21 at 17:23
54

You don't have to specify the global flag. From the documentation, there is a separate parameter ($limit) used to specify the number of replacements to make:

limit The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

So, unless you specify a positive number for this parameter, it will replace all occurrences by default:

$strTmp = preg_replace('~(<\/CharacterStyleRange>(.*?)\n*</CharacterStyleRange>)~im ' , "</CharacterStyleRange>", $strTmp);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
-2

There is a / before the letter G in the string you're replacing.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cparello
  • 607
  • 6
  • 8
  • 1
    this just threw that error for me "Glasshouse Images/Getty Images" My guess is preg_ sees that as an escape char – Cparello Jun 14 '18 at 05:30