views:

28

answers:

2

Ok, so I have this:

$fromArray = array(
"/(\[color=)(.+)(\])/",
"(\[\/color\])");

$toArray = array(
"<span style=\"color:\\2\">",
"</span>");

What that's supposed to do it match all [color= to .

I'm running that, but this is what the source outputs:

<span style="color:red]RED<b>BOLD</b>RED[/color">

When I try to run

[color=red]RED[b]BOLD[/b]RED[/color]

through it.

What's going on? I don't know Regex very well, this is my first Regex. But I just can't figure out why it's creating that ugly source code that doesn't work :(

Does anybody know?

Thank you :)

**In case somebody has NO IDEA what I want to do with that (it's pretty unclear :), here's it:

Translate [color=red] to<span style="color:red;"> Translate [/color] to </span>.

Now I need to do these separately, if I do them as one regex pattern it'll mess up with another issue that would take days to explain :\

+4  A: 

Use the non-greedy quantifier:

$fromArray = array(
"/(\[color=)(.+?)(\])/",
"(\[\/color\])");

What's happening is that your regex for the start tag was actually gobbling up the start tag, the stuff in the middle, and the end tag, because .+ is greedy and matches as much as it can, so the \] was actually matching the bracket at the end of the close tag.

The non-greedy version, .+?, matches as little as possible while still allowing the regex to match, and thus will make sure to only match the open tag.

Amber
Wow, thank you! You're a lifesaver ;)
Jaxo
A: 

Taking into Amber's answer, you can also run it a single line/match like this:

$subject = '[color=red]RED[b]BOLD[/b]RED[/color]';
$result = preg_replace('%\[color=([#a-g0-9]+)\](.+?)\[/color\]%im', '<span style="color:$1">$2</span>', $subject);
Rudisimo