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.

2
  • Is there not a split function for php, such as split("/")[some number]? Commented Jul 21, 2010 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("example.com/"), strlen($url))) and get back an array of stuff Commented Jul 21, 2010 at 20:53

4 Answers 4

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
)
*/
Sign up to request clarification or add additional context in comments.

2 Comments

The “bits” are called segments.
@Gumbo: Variable names changed by request. :P
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));

?>

Comments

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...

Comments

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); 

1 Comment

Don't you mean matches[1], [2], [3] now stores 1,2,3? Remember [0] is always the full pattern match...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.