2012-08-09 111 views
0

我想從使用PHP的preg_match的URL中提取ID ..如何使用preg_match從網址獲取字符串?

對於如:$string = 'http://www.mysite.com/profile.php?id=1111';我爲'1111'

使用的preg_match需要輸出。

我嘗試這樣做:

if(preg_match('/(?:https?):\/\/www\.mysite\.com\/profile\.php\?id\=[0-9]/', $string, $match) > 0){ 

    $id = $match[1]; 
} 

,但我越來越爲 'profile.php'

有人可以幫我請輸出?

+2

爲什麼不用w /'parse_url'呢? – Peon 2012-08-09 06:32:58

+0

你在正則表達式中犯了錯誤,id \ = [0-9]應該寫成id =([0-9] +) – CyberDem0n 2012-08-09 06:35:03

+0

@DainisAbols:不,我想檢查url名稱,如果它的正確只有我需要id .. – Micku 2012-08-09 06:43:55

回答

0

如果只有一個網址參數,您可以使用爆炸函數來做到這一點很容易,像

$string = 'http://www.mysite.com/profile.php?id=1111'; 
$ex=explode('=',$string); 
$id=$ex[1]; 

您也可以使用PHP的parse_url功能。

希望得到這個幫助,

2

爲什麼不使用parse_urlparse_str

$url_component = parse_url($string); 
parse_str($url_component['query'], $output); 
echo $output['id']; 
0
$pattern = '/(?:https?):\/\/www\.mysite\.com\/profile\.php\?id\=([0-9]+)/'; 

這應該做工精細! 但這樣做有parse_url