3

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 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

This will remove a character for every block - 12///3 -> 1/3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.