dongpu1879 2017-07-20 13:28
浏览 99
已采纳

匹配子字符串的子字符串

Input:

Animal {cow.<span>moo</span>} <span>noises</span>

Output:

Animal {cow.moo} <span>noises</span>

How could I match only the <span> inside the braces for replacement? I have got as far as matching everything between the braces with

(?<=\{)(.*?)(?=\})

Any help would be greatly appreciated.

  • 写回答

3条回答 默认 最新

  • drbd65446 2017-07-20 13:32
    关注

    You may use a preg_replace_callback to match the strings in between {...} with a basic regex like '~{[^}]+}~' and then replace what you need inside the callback function:

    $s = 'Animal {cow.<span>moo</span>} <span>noises</span>';
    echo preg_replace_callback('~{[^}]+}~', function($m) {
        return str_replace(["<span>", "</span>"], "", $m[0]);
    }, $s);
    // => Animal {cow.moo} <span>noises</span>
    

    See the PHP demo.

    You may use a preg_replace inside the callback function if you need to replace with a regex.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题