donglv6960 2011-07-11 04:01
浏览 28
已采纳

如何修复PHP中的正则表达式PATHS的路径,而不是破坏URL?

I want to replace // but not ://. I'm using this function to fix broken urls:

function fix ($path)
{
    return preg_replace( "/\/+/", "/", $path );
}

For example:

Input:

a//a//s/b/d//df//a/s/

Output (collapsed blocks of more than one slash):

a/a/s/b/d/df/a/s/

That is OK, but if I pass a URL I break the http:// part, and end up with http:/. For example:

http://www.domain.com/a/a/s/b/d/df/a/s/

I get:

http:/www.domain.com/a/a/s/b/d/df/a/s/

I want to keep the http:// intact:

http://www.domain.com/a/a/s/b/d/df/a/s/
  • 写回答

2条回答 默认 最新

  • dpg98445 2011-07-11 05:19
    关注

    You can solve it rather easily using a negative lookbehind:

    function fix ($path)
    {
        return preg_replace("#(?<!:)/{2,}#", "/", $path);
    }
    

    Note that I've also changed your delimiter from / to #, so you don't have to escape slashes.
    Working example: http://ideone.com/6zGBg

    This can still match the second slash if you have more than two (file://// -> file://). If this is a problem, you can use #(?<![:/])/{2,}#.
    Example: http://ideone.com/T2mlR

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

报告相同问题?

悬赏问题

  • ¥15 如何在sql server里完成筛选
  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了