2011-06-29 51 views
1

我很努力創建一個正則表達式來打印我想要的url部分。用PHP我抓住主域名之後的路徑。他們看起來是這樣的:正則表達式幫助從URL抓取值

this-link-1 
this-is-another-one-3 

我使用攫取這些就像是PHP:

$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; 
$whereami = parse_url($url, PHP_URL_PATH); 
echo $whereami; 

有人可以幫我寫個正則表達式來始終刪除 - #爲WHEREAMI變量?所以,從這個例子$ WHEREAMI將運行後this-linkthis-is-another-one通過表達

回答

4
preg_replace("/-\d+$/", "", $whereami) 

例子:

echo preg_replace("/-\d+$/", "", "this-is-another-one-3"); 

輸出:

this-is-another-one 
+0

是的!這工作很好,有多麼有用,所以我永遠不會學習正則表達式:) – Zac

1

你也可以不用正則表達式:

echo implode('-', explode('-', 'this-link-1', -1)); 

結果:

this-link