Reputation: 9113
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.
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
}
}
}
}
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.
Upvotes: 1
Views: 1509
Reputation: 3701
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
Upvotes: 2