What is the most efficient way to parse individual segments of a URL path?

Say my url is www.example.com/usa/california/redding/

What is the most efficient way to return the following:

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

The actual URL will be unknown and the length / number of segments will be unknown.

+4
source share
3 answers

The most effective way to do this would be to loop through the line, look at each consecutive / character and then click on the array as you move. This algorithm will be O (n) if the string concatenation is also 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 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); } } 
+1
source

Not too elegant, but it does its job:

 <?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); ?> 
+1
source

Using regular expression is the first, although it came to me, but I know that it may not be 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); 

the output will be:

  array ( 0 => '/usa/california/redding/', 1 => '/usa/california/redding/', 2 => '/usa/california/', 3 => '/usa/', ) 

at first this is a coincidence, the rest 3 is a capture.

0
source

Source: https://habr.com/ru/post/1492419/


All Articles