If I have a stored input string that looks like this
http://site.com/param1/value1
how can php extract value1
?
I know how to extract parameters that look like this
http://site.com?param1=value1
but it doesn't work for the format I'm asking about.
Generally you could parse url with parse_url and then explode path by / , and than read second value in array.
You can use a simple string function combination:
$str = "http://site.com/param1/value1";
$tail = substr($str, strrpos($str, "/") + 1);
Or if it's not sure if there is a /
somewhere in the string:
preg_match("#/(\w+)$#", $string, $match);
$tail = $match[1];
For the microoptimizers: this too will generally be faster as the array-explode() workaround.
Fast & Easy:
$url = "http://site.com/param1/value1";
$split_url = explode("/", $url);
$value = $split_url[3];
Looking at some php.net manuals you can easily find this function, that totaly fits your needs
strchr
$url = 'http://example.com/param1/value1';
list($param1, $value1) = array_slice(explode('/', $url), -2, 2);
This will give you param1 and value1 from the example stored in the variables $param1 and $value1.
Look up parse_URL that's the function you want
I would suggest a combination of Trickers and Toby Allens solution
$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', trim($path, '/'));
$value = $segments[2];
If you have multiple key-value-paris you can ensure with trim()
, that the key is always even and the value always odd
$count = count($segments);
$result = array();
for ($i = 0; $i < $count; $i += 2) {
$result[$segments[$i]] = $segments[$i+1];
}
精彩评论