【发布时间】:2015-01-03 11:59:55
【问题描述】:
我正在制作一个脚本,用于将某些特定标签转换为已知且有效的 html,例如
[b] bold [/b] for <span style="font-weight:bold"> bold</span>
[color=red] red text [/color] for <span style="font-color:red"> red</span>
[fs=15]big font[/fs] for <span style="font-size:15px"> big font</font>
and [link=http://www.gooole.com target=new title=goole] google[/link] to be converted to
<a href="http://www.gooole.com" title="goole">google</a>
也可以像 [fs=15] 这样混合它们,这很大。 [color=red] 红色文字[/color] [/fs]
这是我使用的代码-
$str = preg_replace( '/\[b\]/', '<span style="font-weight:bold">', $str );
$str =preg_replace( '/\[\/b\]/', '</span>', $str );
$str= preg_replace( '/\[\/fs\]/', '</span>', $str );
$str= preg_replace( '/\[fs=(.*)\]/', '<span style="font-size:$1px">', $str );
$str= preg_replace( '/\[\/color\]/', '</span>', $str );
$str= preg_replace( '/\[color=(.*)\]/', '<span style="font-color:$1">', $str );
此代码在未嵌套使用时可以正常工作,并且如果标记没有 = 属性,也可以在嵌套中使用。当我使用这样的东西时会出现问题
[fs=15] this is big. [fs=12] this is big. [/fs] [/fs]
它给了我
<span style="font-size:15] this is big. [fs=12px"> this is big. </span> </span>
应该是这样的
<span style="font-size:15px> this is big. <span style="font-size:12px> this is big. </span> </span>
它可以正常工作
[b] hi [i] ok [/i] yes [/b]
请建议我不太了解正则表达式。
【问题讨论】:
-
使用非贪婪匹配:
(.*?) -
@hjpotter92 请查看我编辑的问题。(您的代码运行良好,谢谢,但我需要多一步!)
-
我用了好几次,是否可以只用一个 preg_replace 替换所有代码?
标签: php regex preg-replace preg-replace-callback