【问题标题】:How to have the HTML tags wrapped in the right order in php?如何在 php 中以正确的顺序包装 HTML 标签?
【发布时间】:2019-10-05 20:17:19
【问题描述】:

我有一些不完美的 HTML 代码。例如,我有

<b><i>bold and italic</b></i>

我想让它被层层包裹,即。

<b><i>bold and italic</i></b>

如何在 php 中做到这一点?

【问题讨论】:

    标签: php html regex dom dom-manipulation


    【解决方案1】:

    我们可以匹配两个打开/关闭标签并滑动textContent,然后使用preg_replace替换它:

    $re = '/(<.+>)(<.+>)(.+)(<\/.+>)(<\/.+>)/s';
    $str = '<b><i>bold and italic</b></i>';
    $subst = "$1$2$3$5$4";
    
    $result = preg_replace($re, $subst, $str);
    
    echo $result;
    

    输出

    <b><i>bold and italic</i></b>
    

    正则表达式

    如果这不是您想要的表达方式,您可以在regex101.com 中修改/更改您的表达方式。

    正则表达式电路

    您还可以在jex.im 中可视化您的表达式:

    【讨论】:

    • 谢谢,但可能有 3 个或更多标签,我该如何处理?例如&lt;p&gt;&lt;b&gt;&lt;i&gt;bold and italic&lt;/b&gt;&lt;/i&gt;&lt;/p&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 2020-10-15
    • 1970-01-01
    相关资源
    最近更新 更多