2011-10-03 207 views
0

我需要一段基本上可以完成URL匹配任務的代碼。我在下面列出了兩種情況,以清楚我需要的東西。與查詢字符串匹配的網址

匹配URL可能/不可以包含子目錄,所以有兩種情況。

http://example.com/?pgid=1 
http://example.com/?pgid=1&opt2=2 
http://example.com/?opt2=2&pgid=1 
http://example.com/?pgid=1&opt2=2&opt3=3 
http://example.com/?opt2=2&pgid=1&opt3=3 
http://example.com/?opt2=2&opt3=3&pgid=1 

should match => http://example.com/?pgid=1 

http://example.com/sub-dir/?pgid=1 
http://example.com/sub-dir/?pgid=1&opt2=2 
http://example.com/sub-dir/?opt2=2&pgid=1 
http://example.com/sub-dir/?pgid=1&opt2=2&opt3=3 
http://example.com/sub-dir/?opt2=2&pgid=1&opt3=3 
http://example.com/sub-dir/?opt2=2&opt3=3&pgid=1 

should match => http://example.com/sub-dir/?pgid=1 

我怎樣才能達到上述的事情,幫助表示讚賞。謝謝。

+1

慣於首先懶得告訴我們你做了什麼,以滿足您的需求? – Bhaskar

+0

這將匹配所有網址:'。*'(即,我同意@Bhaskar) – deceze

回答

0

正則表達式馬赫該網址是:\?pgid=1$

據我所知你不想在你的網址中的其他查詢字符串參數。

0

我想你的意思是這樣:

$input = array('http://example.com/?pgid=1', 
       'http://example.com/?pgid=1&opt2=2', 
       'http://example.com/?opt2=2&opt3=3&pgid=1', 
       'http://example.com/sub-dir/?opt2=2&opt3=3&pgid=1'); 


foreach($input as $i){ 

    $url = parse_url($i); 
    echo $url['scheme'].'://'.$url['host'].$url['path']; 
    parse_str($url['query'],$query); 
    echo 'pgid='.$query['pgid']; 
    echo '<br/>'; 

} 

很顯然,你應該調整這對您的個人需要,但是這顯示瞭如何提取pgid與只是參數重建的URL。

然後,您可以進行匹配,可能只需使用$query['pgid']或使用全新的url。

0

可以使用parse_urlparse_str

$url = parse_url('http://example.com/?pgid=1&opt2=2&opt3=3'); 
$against = parse_url('http://example.com/?pgid=1'); 

$folder = $url['path']; 
$query = parse_str($url['query']); 
$pgidout = $pgid; 
$query = parse_str($against['query']); 


if(($url['path'] == $against['path']) && ($pgid == $pgidout)){ 
    echo "matched"; 
} else { 
    echo "not matched"; 
}