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);
精彩评论