dragon87836215 2011-10-10 21:27
浏览 28
已采纳

PHP Regex:选择除最后一次出现之外的所有内容

I'm trying to replace all 's sans that final one with \t in order to nicely indent for a recursive function.

This
that
then
thar
these
them

should become:

This
    that
    then
    thar
    these
them

This is what I have: preg_replace('/ (.+?) /',' \t$1 ',$var);

It currently spits this out:

This
    that
then
thar
these
them

Quick Overview:

Need to indent every line less the first and last line using regex, how can I accomplish this?

  • 写回答

4条回答 默认 最新

  • douciping4283 2011-10-10 21:35
    关注

    After fixing a quotes issue, your output is actually like this:

    This
        that
    then
        thar
    these
    them
    

    Use a positive lookahead to stop that trailing from getting eaten by the search regex. Your "cursor" was already set beyond it so only every other line was being rewritten; your match "zones" overlapped.

    echo preg_replace('/
    (.+?)(?=
    )/', "
    \t$1", $input);
    //          newline-^  ^-text ^-lookahead ^- replacement
    

    Live demo.

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题