如果您使用的是PHP,那么可以这样做。第一个拆分移除了前导
http://www.example.com/
然后第二部分将这些值围绕
/
:
$urls = array('http://www.example.com/first-path',
'http://www.example.com/first-path/second-path',
'http://www.example.com/first-path/second-path/third-path',
'http://www.example.com/something.html',
'http://www.example.com/first-path?id=5');
foreach ($urls as $url) {
$tail = preg_split('#https?://[^/]+/#', $url, -1, PREG_SPLIT_NO_EMPTY)[0];
$paths = preg_split('#/#', $tail);
print_r($paths);
}
输出:
Array
(
[0] => first-path
)
Array
(
[0] => first-path
[1] => second-path
)
Array
(
[0] => first-path
[1] => second-path
[2] => third-path
)
Array
(
[0] => something.html
)
Array
(
[0] => first-path?id=5
)
在javascript中也可以做类似的事情:
let urls = ['http://www.example.com/first-path',
'http://www.example.com/first-path/second-path',
'http://www.example.com/first-path/second-path/third-path',
'http://www.example.com/something.html',
'http://www.example.com/first-path?id=5'];
console.log(urls.map(s => s.split(/https?:\/\/[^\/]+\//)[1].split(/\//)))
输出:
Array(5) [â¦] â
0: Array [ "first-path" ]
1: Array [ "first-path", "second-path" ]
2: Array(3) [ "first-path", "second-path", "third-path" ]
3: Array [ "something.html" ]
4: Array [ "first-path?id=5" ]