91

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,030
  • 21
  • 100
  • 124
Foo Ling
  • 971
  • 1
  • 6
  • 8

3 Answers3

188

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

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
rid
  • 57,636
  • 30
  • 143
  • 185
  • See [the other good answer](https://stackoverflow.com/a/19061066/114558) on this question for more background. – rinogo Nov 27 '21 at 17:23
51

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,030
  • 21
  • 100
  • 124
p.s.w.g
  • 141,205
  • 29
  • 278
  • 318
-2

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

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Cparello
  • 67
  • 1
  • 6
  • 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