1

The follwing code gives me an error "preg_replace() [function.preg-replace]: Unknown modifier '?'"

$str = 'background: url("../../dsdgsd/contain.jpg");';

echo preg_replace('/url\s?\(\s?(\"|\')([../?]*[a-z/]*?[/?]?)([a-z0-9_-]*[.][jpg|jpeg|png|jpeg]*)([\'|\"]\))/gi','url("../images/$3")',$str);
Saiful Neo
  • 51
  • 1
  • 3
  • How familiar are you with the [regex syntax](http://us.php.net/manual/en/regexp.reference.delimiters.php)? Either use a delimiter that's less likely to occur in the pattern itself, e.g. `#`, or escape every instance of `/` in the pattern. – DCoder Sep 19 '12 at 09:27
  • 2
    Whoever wrote this regexp, mixed up `[` and `(` (apart from various other issues). E.g. this: `[../?]*` should probably read `(\\.\\./)*`, i.e. "a repeated occurrence of `../`" – mvds Sep 19 '12 at 09:32

3 Answers3

2

I'm not sure what this regexp is supposed to be doing, but the error is given because you have / characters in the pattern. The parser then thinks your pattern is done, and takes everything after it (which is ? in this case) as modifier. Hence the error.

Fix by using another separator: (most people use # when dealing with a lot of /)

echo preg_replace('#url\s?\(\s?(\"|\')([../?]*[a-z/]*?[/?]?)([a-z0-9_-]*[.][jpg|jpeg|png|jpeg]*)([\'|\"]\))#i','url("../images/$3")',$str);

(apart from this, as has been mentioned, the g modifier is not needed)

mvds
  • 45,755
  • 8
  • 102
  • 111
1

For preg_replace, it is not necessary to use the global modifier g (should not use), it already replace globally.

There is no g modifier in php.

xdazz
  • 158,678
  • 38
  • 247
  • 274
1

Since you start the regex with a / character, it is a delimiter, and you should escape all occurrences of / inside the regex. Because the first character after the second / is ?, it is interpreted as a modifier.

gpvos
  • 2,722
  • 1
  • 17
  • 22