Tutorial :Parse URL with Regex using PHP



Question:

I have a url formatted like this:

http://www.example.com/detail/state-1/county-2/street-3

What I'd like to do is parse out the values for state (1), county (2), and street (3). I could do this using a combination of substr(), strpos(), and a loop. But I think using a regex would be faster however I'm not sure what my regex would be.


Solution:1

$pieces = parse_url($input_url);  $path = trim($pieces['path'], '/');  $segments = explode('/', $path);    foreach($segments as $segment) {      $keyval = explode('-', $segment);      if(count($keyval) == 2) {          $key_to_val[$keyval[0]] = $keyval[1];      }  }    /*  $key_to_val: Array (      [state] => 1,      [county] => 2,      [street] => 3  )  */  


Solution:2

Could just do this:

<?php    $url = "http://www.example.com/detail/state-1/county-2/street-3";  list( , $state, $country, $street) = explode('/', parse_url($url, PHP_URL_PATH));    ?>  


Solution:3

if (preg_match_all('#([a-z0-9_]*)-(\\d+)#i', $url, $matches, PREG_SET_ORDER)) {      $matches = array(          array(              'state-1',              'state',              '1',          ),          array(              'county-2',              'county',              '2',          ),          array(              'street-3',              'street',              '3',          )      );  

}

Note, that's the structure of the $matches array (what it would look like if you var_dump'd it...


Solution:4

This regex pattern should work:

$subject = 'http://www.example.com/detail/state-1/county-2/street-3';  $pattern = 'state-(\\d+)/county-(\\d+)/street-(\\d+)';    preg_match($pattern, $subject, $matches);  // matches[1],[2],[3] now stores (the values) 1,2,3 (respectively)    print_r($matches);   

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »