BBCODE IMG 标签变体与正则表达式



我需要将BBCODE IMG标签转换为HTML。 问题是:IMG TAG有多种变体。

[img]img_patch[/img]
[img=200x150]img_patch[/img]
[img width=200 height=150]img_patch[/img]
[img=width=200xheight=150]img_patch[/img]
[img width=200]img_patch[/img]

下面的正则表达式涵盖了第一个和第二个。

'#[img](.+)[/img]#Usi',
'#[img=?(d+)?x?(d+)?](.*?)[/img]#Usi',

我需要其他变体的帮助,或者在唯一的 REGEX 中转换所有变体。 我非常感谢您的帮助!

这应该涵盖所有情况:

<?php
$data = <<<DATA
[img]img_patch[/img]
[img=200x150]img_patch[/img]
[img width=200 height=150]img_patch[/img]
[img=width=200xheight=150]img_patch[/img]
[img width=200]img_patch[/img]
DATA;
$regex = '~
(?P<tag>[img[^][]*])
(?P<src>.+?)
[/img]
~x';
$inner = '~b(?P<key>width|height)?=(?P<value>[^s]]+)~';
$values = '~d+~';
$data = preg_replace_callback($regex,
function($match) use($inner, $values) {
$attr = [];
preg_match_all($inner, $match['tag'], $attributes, PREG_SET_ORDER);
foreach($attributes as $attribute) {
if (!empty($attribute["key"])) $attr[$attribute["key"]] = $attribute["value"];
else {
preg_match_all($values, $attribute["value"], $width_height);
list($attr["width"], $attr["height"]) = array($width_height[0][0], $width_height[0][1]);
}
}
// do the actual replacement here
$attr["src"] = $match["src"];
$ret = "<img";
foreach ($attr as $key => $value) $ret .= " $key='$value'";
$ret .= '>';
return $ret; 
},
$data);
echo $data;
?>

和产量

<img src='img_patch'>
<img height='150' width='200' src='img_patch'>
<img width='200' height='150' src='img_patch'>
<img height='150' width='200' src='img_patch'>
<img width='200' src='img_patch'>

该代码使用多步骤方法:首先匹配所有标记,然后分析属性。最后,形成新字符串。

查看有关 ideone.com 的演示


注意:与你的(昵称)儿子相反,现在你确实知道一些事情,不是吗?

嘿,简,我真的很感谢你的帮助!是的,我不是什么都知道,但我知道一些事情。实际上,我已经创建了以下REGEX,并且工作正常,涵盖了所有IMG TAG:

'#[img=(.+)]#Usi',
'#[img=+(d+)x+(d+)](.+)[/img]#Usi',
'#[img[s|=]+[width=]+([0-9]+)?[s|x]+[height=]+([0-9]+)](.+)[/img]#Usi',
'#[img[s]+[width=]+([0-9]+)](.+)[/img]#Usi',

我希望这篇文章可以帮助其他人完成自己的项目!

最新更新