0

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.

ashansky
  • 730
  • 2
  • 14
  • 34
  • Is there not a split function for php, such as split("/")[some number]? – Anders Jul 21 '10 at 20:47
  • actually explode() would be the fastest way as it doesn't use regex matching.... since you are using a url which is delimited across /'s you can use explode("/", substr($url, strlen("http://www.example.com/"), strlen($url))) and get back an array of stuff – Elf King Jul 21 '10 at 20:53

4 Answers4

3
$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
)
*/
Amber
  • 507,862
  • 82
  • 626
  • 550
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));

?>
Marco Ceppi
  • 7,163
  • 5
  • 31
  • 43
0
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...

ircmaxell
  • 163,128
  • 34
  • 264
  • 314
0

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); 
sigint
  • 316
  • 2
  • 6
  • Don't you mean `matches[1], [2], [3] now stores 1,2,3`? Remember `[0]` is always the full pattern match... – ircmaxell Jul 21 '10 at 21:00