tags:

views:

46

answers:

4

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.

+3  A: 
$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
The “bits” are called segments.
Gumbo
@Gumbo: Variable names changed by request. :P
Amber
This is awesome thanks!
ashansky
+2  A: 

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
A: 
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
A: 

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
Don't you mean `matches[1], [2], [3] now stores 1,2,3`? Remember `[0]` is always the full pattern match...
ircmaxell