正則表達式:修復重複的斜杠而不影響協議
假設您要修復如下所示的 URL:
https://www.example.com/my/path//to-file.jpg
使用字符串替換或簡單的正則表達式可能會錯誤地“修復”協議後面的雙斜杠。我們可以通過使用負面的lookbehind來解決這個問題。
(?<!:)/+
對於 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
對於 Javascript:
let url = 'https://www.example.com/my/path//to-file.jpg';
url.replaceAll(/(?<!:)\/+/gm, '/');
// "https://www.example.com/my/path/to-file.jpg"