Sahil 的方法非常复杂,包含 6 个替换元素、模式中不必要的字符转义以及不需要的重复字符的有限量词。其实这个简单的 url 没能更正:http://example.com//path1
改为在您的项目中实施这种更短、更快、更简洁、更易读的方法:
代码(Demo):
$urls=array(
"http://example.com//path/",
"http://example.com/path/?&",
"http://example.com/path/?¶m=one",
"http://example.com///?&",
"http://example.com/path/subpath///?param=one&");
$urls=preg_replace(
['/(?<!:)\/{2,}/','/\?&/','/[?&]$/'],['/','?',''],$urls);
var_export($urls);
输出:
array (
0 => 'http://example.com/path/',
1 => 'http://example.com/path/',
2 => 'http://example.com/path/?param=one',
3 => 'http://example.com/',
4 => 'http://example.com/path/subpath/?param=one',
)
模式解释:
/(?<!:)\/{2,}/ 匹配 2 个或多个不带冒号的斜线;用单斜杠替换。
/\?&/ 匹配一个问号后跟一个 & 号;替换为问号。
/[?&]$/如果是问号或&,则匹配最后一个字符;删除。
另外,这是我对 url 解析方法的看法:(Demo)
代码:
$urls=array(
"http://example.com//path//to///dir////4/ok",
"http://example.com/path/?&&",
"http://example.com/path/?¶m=one",
"http://www.example.com///?&",
"http://example.com/path/subpath///?param=one&");
foreach($urls as $url){
$a=parse_url($url);
$clean_urls[]="{$a["scheme"]}://{$a["host"]}". // no problems expected from these elements
preg_replace('~/+~','/',$a["path"]). // reduce multiple consecutive slashes to single slash
(isset($a["query"]) && trim($a["query"],'&')!=''?'?'.trim($a["query"],'&'):''); // handle querystring
}
var_export($clean_urls);
输出:
array (
0 => 'http://example.com/path/to/dir/4/ok',
1 => 'http://example.com/path/',
2 => 'http://example.com/path/?param=one',
3 => 'http://www.example.com/',
4 => 'http://example.com/path/subpath/?param=one',
)
url组件处理说明:
path 元素上的 preg_replace() 模式将匹配 1 个或多个斜杠并将它们替换为单个斜杠。这也可以使用~/+(?=/)~ 或~(?<=/)/+~ 和一个空的替换字符串来实现,但是环视至少比无环模式慢2.5 倍。
query 处理行有一个内联条件,首先检查query 元素是否存在,然后...
如果是这样,它将从两端修剪无限的&符号并检查修剪后的值是否不为空。任何符合条件的字符串都将去掉 & 号,并在前面加上一个问号。
如果不是,则将一个空字符串附加到要推送到$clean_urls的字符串中。