开发者

Having some trouble with Regex

Ok, so I have this:

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

$toArra开发者_JS百科y = 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 :\


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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜