Regex: Fix duplicate slashes without affecting protocol
Matt Kenefick
Posted on May 13, 2021
Let’s say you want to fix a URL that looks like:
https://www.example.com/my/path//to-file.jpg
Using a string replace or a simple regex could incorrectly “fix” the double slashes following the protocol. We can fix that by using a negative lookbehind.
(?<!:)/+
For PHP:
<?php
$url = 'https://www.example.com/my/path//to-file.jpg';
$str = preg_replace('#(?<!:)/+#im', '/', $url);
// https://www.example.com/my/path/to-file.jpg
```
### For Javascript:
```
let url = 'https://www.example.com/my/path//to-file.jpg';
url.replaceAll(/(?<!:)\/+/gm, '/');
// "https://www.example.com/my/path/to-file.jpg"
```
💖 💪 🙅 🚩
Matt Kenefick
Posted on May 13, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.