开发者

How to fix a path with regex in php for PATHS and not break URLs?

开发者 https://www.devze.com 2023-03-19 11:54 出处:网络
I want to replace // but not ://. I\'m using this function to fix broken urls: func开发者_运维问答tion fix ($path)

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

func开发者_运维问答tion 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/


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


return preg_replace("/[^:]\/+/", "/", $path);
0

精彩评论

暂无评论...
验证码 换一张
取 消