-1

I get this error:

preg_replace(): Unknown modifier 'g' in

On this code:

$text = preg_replace("/\\[img]([^\\[]*)\\[/img]/","<img src=\"\\1\" border=\"0\">",$text); 

Help anyone?

EDIT: My goal with this is when i use

[img]http://google.com/img.png[/img] 

in a comment field the output should be something like

<img src="http://google.com/img.png"/>
user3368977
  • 35
  • 2
  • 6
  • 2
    There are a few problems with this. What is your goal? It looks like you may be trying to replace `[img]...[/img]` and with a proper `` tag. The unknown modifier error is due to `[/img]` prematurely ending your regex. If we know the input and expected output, we can help more effectively. – Michael Berkowski Mar 07 '15 at 21:04
  • This is for a comment system. When the use [img] in the comment field it will turn to . If you understand. Im not very good at English so excuse me for that :P – user3368977 Mar 07 '15 at 21:07
  • Unescaped `/` indicates end of the regexp, giving switches of `i`, `m` and `g`.... `i` and `m` are actually both valid regexp switches, but `g` isn't – Mark Baker Mar 07 '15 at 21:07
  • Please edit your question above to show a specific example of the input and output string., like `[img]stuff[/img]` output as `` – Michael Berkowski Mar 07 '15 at 21:08

2 Answers2

0

You have to escape all occurances of / inside the outer / delimiters of your regex.

So you are probably looking for this:

preg_replace("/\\[img]([^\\[]*)\\[\/img]/",
             "<img src=\"\\1\" border=\"0\">",
             $text); 

Otherwise the regex engine will treat the expression as terminated here at the second /:

/\\[img]([^\\[]*)\\[/

Whatever follows will be treated as modifiers to the expression. i and m do exist, g does not exist. That is why an error is thrown whilst compiling the regex.

Alternatively you can use another delimiter character beside /. But you have to make sure that character does not occur unescaped inside the expression itself. If the expression is not a literal string but comes from a variable then the preg_quote() function comes in handy.

arkascha
  • 41,620
  • 7
  • 58
  • 90
0

Just use a different start/end regex character (for example: `):

$text = preg_replace("`\\[img]([^\\[]*)\\[/img]`","<img src=\"\\1\" border=\"0\">", $text);
engine9pw
  • 364
  • 1
  • 5