正则表达式 - 删除[image =] [/ image] BB标记

时间:2016-12-06 20:15:05

标签: php regex

在脚本中,我有一个BB图像代码,可以使用以下两种格式之一:

[image=http://i459.photobucket.com/albums/xxx/enkidu-wd/test/38602_450pom.jpg][/image] (without Alt text)

[image=https://m.photobucket.com/enkidu-wd/test/38602_450pomnik.jpg]alt text[/image] (with Alt text)

我的目标是始终删除这四个字符:$ & ' " - 但只有这些字符被添加为替代文字(即[image=...]ALT TEXT[/image]之间)。如果这些字符出现在$ text消息中[image][/image]标记之外的任何位置,则应忽略它们(不删除)。

我尝试使用preg_replace,如下所示,但它不起作用。请注意$ text是一条消息,可能包含也可能不包含此[image] [/ image]标记。

$start = '\[image=';
$end  = '\[\/image\]';
$text = preg_replace(
    '#('.$start.')(.*)('.$end.')#i',
    '$1'.str_replace(array('$','&','\'','"'),'').(*).'$3',
    $text
);

1 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

$pattern = '~(?:\G(?!\A)|[image\b[^]]*])[^[$&\'"]*\K[$&\'"]~i';

如果图像标签之间可以包含其他BBCODE标签,您可以这样更改:

$pattern = '~(?:\G(?!\A)|[image\b[^]]*])[^[$&\'"]*(?:\[(?!/image\b)[^][]*][^[$&\'"]*)*\K[$&\'"]~i';

使用:

$result = preg_replace($pattern, '', $yourstring);

细节:

~ # pattern delimiter
(?:
    \G(?!\A) # contiguous to the previous match, not at the start of the string
  | # OR
    [image\b[^]]*] # an opening image tag
)
[^[$&\'"]* #"# all that isn't an opening square bracket or one the chars
\K # remove all that has been matched before from the match result
[$&\'"]
~i

说明:

由于[^[$&\'"]*禁止打开方括号,一旦达到结束[/image],连续性就会中断,\G锚点会失败。唯一的方法是找到另一个开放[image...]标记。