请原谅我在正则表达方面没有更好的表现。
道歉:示例已更新
我正在使用PHP脚本在phpBB论坛中清理一些垃圾。 phpBB使用某种键对bbcode进行编码,这是一个冒号后出现的8位数字符串。这是一个例子:
outer [size=5:24f81ld3]inner text[/size:24f81ld3] outer
我试图去掉大小是一个字符而不是两个字符的位置,所以上面会变成:
outer inner text outer
但是这个:
outer [size=100:24f81ld3]inner text[/size:24f81ld3] outer
NOT 会变成这样:
outer inner text outer
感谢任何帮助!
答案 0 :(得分:1)
这是代码
function remove_phpbb_garbage($str)
{
return preg_replace('/\[size=[0-9a-z](?::[0-9a-z]+)?\]((?:[^\[]|\[(?!\/size))*)\[\/size(?::[0-9a-z]+)?\]/i', '\1', $str);
}
以下是测试用例:
echo remove_phpbb_garbage("outer [size=1]inner text[/size] outer"), "\n";
echo remove_phpbb_garbage("outer [size=5:24f81ld3]inner text[/size] outer"), "\n";
echo remove_phpbb_garbage("outer [size=100:24f81ld3]inner text[/size] outer"), "\n";
echo remove_phpbb_garbage("outer [size=100:24f81ld3]inner text[/size] outer"), "\n";
echo remove_phpbb_garbage("outer [size=5:24f81ld3]inner text[/size:24f81ld3] outer"), "\n";
echo remove_phpbb_garbage("outer [size=100:24f81ld3]inner text[/size:24f81ld3] outer"), "\n";
echo remove_phpbb_garbage("[b:2q9o3yfx][size=2:2q9o3yfx][font=Arial:2q9o3yfx]Please be careful on how to Jail break your Iphone. In case if you are not already did it. There is a lot of specific instructions How to Jail break your phone on the web. Please read up before attempting a Jail break.[/font:2q9o3yfx][/size:2q9o3yfx][/b:2q9o3yfx] _________________ [bg2ads1:2q9o3yfx][/bg2ads1:2q9o3yfx]"), "\n";
这是输出:
outer inner text outer
outer inner text outer
outer [size=100:24f81ld3]inner text[/size] outer
outer [size=100:24f81ld3]inner text[/size] outer
outer inner text outer
outer [size=100:24f81ld3]inner text[/size:24f81ld3] outer
[b:2q9o3yfx][font=Arial:2q9o3yfx]Please be careful on how to Jail break your Iphone. In case if you are not already did it. There is a lot of specific instructions How to Jail break your phone on the web. Please read up before attempting a Jail break.[/font:2q9o3yfx][/b:2q9o3yfx] _________________ [bg2ads1:2q9o3yfx][/bg2ads1:2q9o3yfx]
重要提示:该功能不正确处理嵌套size
标签!
如果您对正则表达式感兴趣,这个精彩的资源涵盖了所有细节和风格: http://www.regular-expressions.info/
答案 1 :(得分:0)
以下正则表达式只有在大小标签的值恰好是一个字符时才会匹配。
正则表达式:
\[(size)=[^:]:([^\]\[]*)\]([^\[\]]*)\[\/\1:\2]
替换字符串:
$3
代码将是,
preg_replace('~\[(size)=[^:]:([^\]\[]*)\]([^\[\]]*)\[\/\1:\2]~', '$3', $str);