php – 解析URL路径的特定段的最有效方法是什么?

说我的网址是www.example.com/usa/california/redding/

返回以下内容的最有效方法是什么:

$urls = array ( 0 => '/usa/', 1 => '/usa/california/', 2 => '/usa/california/redding/' ); 

实际的URL将是未知的,并且段的长度/数量将是未知的.

最佳答案 执行此操作的最有效方法是循环遍历字符串,查找每个连续/字符,然后随时将它们推送到数组上.该算法将为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);
  }
}
点赞