假设我的网址是www.example.com/usa/california/redding/
返回以下内容的最有效方法是什么:
$urls = array ( 0 => '/usa/', 1 => '/usa/california/', 2 => '/usa/california/redding/' );
实际的 URL 将是未知的,段的长度/数量将是未知的。
假设我的网址是www.example.com/usa/california/redding/
返回以下内容的最有效方法是什么:
$urls = array ( 0 => '/usa/', 1 => '/usa/california/', 2 => '/usa/california/redding/' );
实际的 URL 将是未知的,段的长度/数量将是未知的。
不太优雅,但这可以完成工作:
<?php
$link = 'www.example.com/usa/california/redding/';
$parts = explode('/',$link);
$results = array();
for ($i = 1; $i < count($parts) - 1; $i++) {
$results[] = '/'.implode('/', array_slice($parts, 1,$i)).'/';
}
print_r($results);
?>
最有效的方法是遍历字符串,查看每个连续的 / 字符,然后将它们推送到数组中。假设字符串连接也是 O(n),该算法将是 O(n)。
$url = "www.example.com/usa/california/redding/";
$next = "";
$urls = array();
// we use the strpos function to get position of the first /
// this let's us ignore the host part of the url
$start = strpos($url, "/");
// just in case PHP uses C strings or something (doubtful)
$length = strlen($url);
// loop over the string, taking one character at a time
for ($i = $start; $i < $length; $i++) {
// append the character to our temp string
$next .= $url[$i];
// skip the first slash, but after that push the value of
// next onto the array every time we see a slash
if ($i > $start && $url[$i] == "/") {
array_push($urls, $next);
}
}
使用regular expression
是第一个虽然来找我,但我知道它可能不是efficient
:
$str = 'www.example.com/usa/california/redding/';
$patten = '/(((\/.[0-9A-Za-z]+\/).[0-9A-Za-z]+\/).[0-9A-Za-z]+\/)/';
$ret = preg_match($patten, $str, $matches);
var_export($matches);
输出将是:
array (
0 => '/usa/california/redding/',
1 => '/usa/california/redding/',
2 => '/usa/california/',
3 => '/usa/',
)
第一个是全场比赛,剩下的3个是捕获。