简体   繁体   中英

How to get an ID from an URL using preg_match?

Problem

I am currently doing a preg_match on an url. This url has a certain id in the second parameter or the third parameter. However I don't know how I could get this more efficiently.

Code

preg_match('~http://www.example.com/some/(.+?)/~is', $url, $id);
if (!isset($id[1])) {
    preg_match('~http://www.example.com/some/thing/(.+?)/~is', $url, $id);
    if (!isset($id[1])) {
        preg_match('~http://www.example.com/some/other/(.+?)/~is', $url, $id);
        if (!isset($id[1])) {
            preg_match('~http://www.example.com/some/thingelse/(.+?)/~is', $url, $id);
            if (!isset($id[1])) {
                return false
            }
        }
    }
}

What I would like to do

if (preg_match('~http://www.example.com/some/(.+?)/~is', $url, $id)) {
    $id = $id[1];
} else if (preg_match('~http://www.example.com/some/(.+?)/(.+?)/~is', $url, $id)) {
    $id = $id[1];
} else {
    return false;
}

However, this doesn't seem to work.

If the following regular expressions in fact did work as you wanted them to

if (preg_match('~http://www.example.com/some/(.+?)/~is', $url, $id)) {
    $id = $id[1];
} else if (preg_match('~http://www.example.com/some/(.+?)/(.+?)/~is', $url, $id)) {
    $id = $id[1];
} else {
    return false;
}

... then you would never reach the second case anyway. The match will already be made in the first RegEx, as the beginning or the second expression is identical to the first expression. And even if you turned them around you would always get the id from the first parameter/path part, as you set $id = $id[1] on both results.

As stated in the comments, you probably would be better off using parse_url for this instead:

$urls = [
    'http://www.example.com/some/thingelse/foo/bar/baz/',
    'http://www.example.com/some/foo/bar/baz/',
];

foreach ($urls as $url) {
    echo "Checking $url", PHP_EOL;

    $path = parse_url($url, PHP_URL_PATH);
    $parts = explode('/', $path);

    echo "Second parameter: ", $parts[2], PHP_EOL;
    echo "Third parameter:  ", $parts[3], PHP_EOL;
}

Output:

Checking http://www.example.com/some/thingelse/foo/bar/baz/
Second parameter: thingelse
Third parameter:  foo

Checking http://www.example.com/some/foo/bar/baz/
Second parameter: foo
Third parameter:  bar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM