Preg_正确替换多个bbcode
目前,我正在创建一个 bbCodes 函数,以将所有 bbCodes 替换为文本中相应的 HTML 代码。我的代码像这样工作 atm:
public function bbCodes($text) {
global $bb_codes;
$text = preg_replace(array_keys($bb_codes), array_values($bb_codes), $text);
return $text;
}
其中 $bb_codes 看起来像这样:
$bb_codes = array(
"/\[b\](.*)\[\/b\]/is" => "<b>$1</b>",
"/\[u\](.*)\[\/u\]/" => "<u>$1</u>",
"/\[i\](.*)\[\/u\]/" => "<i>$1</i>",
"/\[d\](.*)\[\/d\]/" => "<del>$1</del>",
"/\[url=(.*)\](.*)\[\/url\]/" => "<a href='$1'>$2</a>"
);
当每个 bbcode 仅使用一次时它就可以工作,例如:
[b]this text is bold[/b]
[i]this text is italic[/i]
etc..
但是一旦我多次使用一个 bbcode 标签,它就会变得混乱:
[b]this text is bold[/b]
[i]this text is italic[/i]
[b]this text is bold too[/b]
它会看到第一个 [b]标签并查找另一个 [/b] 标签,但它会采用最后一个标签,而不是遇到的第一个标签(在上面的示例中,所有文本都将变为粗体,第一个 [b] 和最后一个 [/b] 将仅被替换)。有谁知道我做错了什么以及如何解决这个问题?
提前致谢!
干杯。
Currenlty I'm creating a bbCodes function to replace all bbCodes by their corresponding HTML codes within a text. My code works like this atm:
public function bbCodes($text) {
global $bb_codes;
$text = preg_replace(array_keys($bb_codes), array_values($bb_codes), $text);
return $text;
}
where $bb_codes looks like this:
$bb_codes = array(
"/\[b\](.*)\[\/b\]/is" => "<b>$1</b>",
"/\[u\](.*)\[\/u\]/" => "<u>$1</u>",
"/\[i\](.*)\[\/u\]/" => "<i>$1</i>",
"/\[d\](.*)\[\/d\]/" => "<del>$1</del>",
"/\[url=(.*)\](.*)\[\/url\]/" => "<a href='$1'>$2</a>"
);
It's working when each bbcode is only used once, e.g.:
[b]this text is bold[/b]
[i]this text is italic[/i]
etc..
But as soon as I use one bbcode tag multiple times it gets messed up:
[b]this text is bold[/b]
[i]this text is italic[/i]
[b]this text is bold too[/b]
It will see the first [b] tag and look for another [/b] tag but it takes the last one instead of the first one it encounters (in the above example all the text will be bold and the first [b] and last [/b] will be replaced only). Does anyone know what I've done wrong and how I can fix this?
Thanks in advanced!
Cheers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你需要使用非贪婪通配符,而不是把所有
.*
都写成.*?
。You need to use non greedy wildcard, instead of all the
.*
write.*?
.为什么你不使用 BBCode Parser ?
查看 NBBC 解析器。
要安装它,只需将其放入服务器上的有用文件夹中,然后像我稍后提供的链接中所写的那样连接它:)
Why you're not using BBCode Parser ?
Look at NBBC Parser.
To install it just put it into usefull folder on your server and connect it like it written in link I've provided later : )