2014-01-20 42 views
0

的一部分,我現行主要使用ereg_replacepreg_replace函數來獲得URL

$myurl="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; 
$theid= ereg_replace("[^0-9]", "", $myurl); 

要在網址的結尾得到一個ID進入

我還想用的preg_replace,完成越來越兩類ids

一看起來像http:// site.com?id = 64

lik Ë我做以上

,但我想也得到一個將包含HTTP:// site.com?pick=7878787

我想挑分配ID的一個變量,名爲$ thepickupcode

另一個變量稱爲$ theid

任何幫助,我很高興。

回答

0

你的問題不太清楚,但我覺得你想要的東西,如:

然後你想要的preg_match,而不是替代。

preg_match('~(pick|id)=(.+)~i', $myurl, $res); 
print_r($res); 

我不知道所有的可能性,但是這可能是比較合適的:

preg_match('~\?(pick|id)=([0-9]+)$~i', $myurl, $res); 
print_r($res); 
+0

這似乎沒有做到這一點? 我有兩個可能在我的網站的結尾 .com /?id = 74或.com /?pick = 838390 當然數字的變化,但我想提取它們到變量,所以我可以指導PHP到那個ID或那個選擇 – Silhouett

+0

謝謝你們所有的幫助,這些都是很好的學習例子,可以嘗試和測試。 – Silhouett

1

非正則表達式的方法:

$res = parse_url($myurl); 
parse_str($res['query'], $query); 
$theid = $query['id']; 
$thepickupcode = $query['pick']; 

一個正則表達式的方法:

if (preg_match('~(?<=[?&])(id|pick)=([0-9]++)(?=&|$)~', $_SERVER['REQUEST_URI'], $match)) 
    if ($match[1] == 'id') $theid = $match[2]; 
    else $thepickupcode = $match[2]; 
0

當你想改變ereg...preg...,你必須把正則表達式放在分隔符中。
對於示例:

$theid= ereg_replace("[^0-9]", "", $myurl); 

變爲:

$theid = preg_replace("/[^0-9]/", "", $myurl); 

$theid = preg_replace("/\D+/", "", $myurl); 

但是這會給你錯誤的結果,如果有其他數字比ID。

我建議你按照@CasimiretHippolyte的回答。