【问题标题】:BBCODE IMG TAG variations with REGEX带有 REGEX 的 BBCODE IMG TAG 变体
【发布时间】:2018-06-27 00:11:25
【问题描述】:

我需要将 BBCODE IMG TAG 转换为 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 regex image tags bbcode


【解决方案1】:

这应该涵盖所有情况:

<?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'>

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

a demo on ideone.com


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

【讨论】:

    【解决方案2】:

    嘿,简,我真的很感谢你的帮助!是的,我不知道一切,但我知道一些事情。实际上我已经创建了以下 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',
    

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

    【讨论】:

      猜你喜欢
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多