我有一個網址,格式如下:解析URL與正則表達式使用PHP
http://www.example.com/detail/state-1/county-2/street-3
我希望做的是解析出值狀態(1),縣(2),和街道(3)。 ) 我可以做到這一點使用SUBSTR(組合,strpos(),和一個循環。但我認爲使用正則表達式會更快,但我不確定我的正則表達式會是什麼。
我有一個網址,格式如下:解析URL與正則表達式使用PHP
http://www.example.com/detail/state-1/county-2/street-3
我希望做的是解析出值狀態(1),縣(2),和街道(3)。 ) 我可以做到這一點使用SUBSTR(組合,strpos(),和一個循環。但我認爲使用正則表達式會更快,但我不確定我的正則表達式會是什麼。
$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
)
*/
可能只是這樣做:
<?php
$url = "http://www.example.com/detail/state-1/county-2/street-3";
list(, $state, $country, $street) = explode('/', parse_url($url, PHP_URL_PATH));
?>
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',
)
);
}
注意,那是$matches
陣列(它會是什麼樣子,如果你var_dump
倒是它的結構.. 。
這個正則表達式應該工作:
$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],[2],[3]現在存儲1,2,3'?請記住'[0]'始終是完整的模式匹配... – ircmaxell 2010-07-21 21:00:14
是否有不爲PHP分割功能,如分裂(「/」)[一定數量]? – Anders 2010-07-21 20:47:23
實際explode()將是最快的方式,因爲它不使用正則表達式匹配....因爲您使用的是跨越/的分隔的url,您可以使用explode(「/」,substr($ url,strlen (「http://www.example.com/」),strlen($ url)))並獲取一組東西 – 2010-07-21 20:53:13