dquv73115 2017-11-20 16:38
浏览 43
已采纳

如何在字符串中搜索<a>内的<span>并用PHP解包

What is the best way to reformat the HTML with PHP. Put span tag outside of a tag?

This:

<p style="text-align:center">
    <a href="#" target="_blank"><span style="color:green">Text Link</span></a>
</p>

To:

<p style="text-align:center">
    <span style="color:green"><a href="#" target="_blank">Text Link</a></span>
</p>
  • 写回答

1条回答 默认 最新

  • douyalin2258 2017-11-20 17:09
    关注

    You can make a good use of preg_match function:

    $str = '<p style="text-align:center">
                <a href="#" target="_blank"><span style="color:green">Text Link</span></a>
            </p>';
    
    if(preg_match('/^(\<p.*?\>).*(\<a.*?\>).*(\<span.*?\>)([0-9a-zA-Z ]*).*$/is', $str, $regs)) 
    {
        // $regs = [
        //    0 => ... (original string)
        //    1 => '<p style="text-align:center">',
        //    2 => '<a href="#" target="_blank">',
        //    3 => '<span style="color:green">',
        //    4 => 'Text Link']
        $newStr = $regs[1].$regs[3].$regs[2].$regs[4].'</a></span></p>';
    }
    

    You may have to change the [0-9a-zA-Z ]* in regular expression to match your links format.

    If input HTML is multiple line text then you have to use s modifier after the regular exception, I also used i as case insensitive just to be sure noone mixed <P> and <p> tag together and so on...

    Note that this if fairly specific solution and for more general solution you should use something like loading HTML into DOM and working with nodes, but this is pretty simple and quick solution for this particular case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么