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 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?
  • ¥15 (SQL语句|查询结果翻了4倍)
  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用
  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚