2011-02-07 108 views
0

我試圖用preg_match從以下URL中獲取12345。文本和第一次出現之間的PHP preg_match -

$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html"; 

$beg = "http://www.somesite.com/directory/"; 
$close = "\-"; 
preg_match("($beg(.*)$close)", $url, $matches); 

我試過了多種組合。 *? \ b

有誰知道如何從preg_match中提取12345的URL嗎?

回答

3

有兩件事,首先,你需要preg_quote,你也需要分隔符。使用您的施工方法:

$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html"; 

$beg = preg_quote("http://www.somesite.com/directory/", '/'); 
$close = preg_quote("-", '/'); 
preg_match("/($beg(.*?)$close)/", $url, $matches); 

不過,我會寫查詢略有不同:

preg_match('/directory\/(\d+)-/i', $url, $match); 

它只目錄部分匹配的,是更具可讀性,並確保你只能得到數字後面(無弦)

+0

謝謝,完美的作品! – Mark 2011-02-07 20:17:15

1

這不使用的preg_match,但會達到同樣的事情,會執行得更快:

$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html"; 

$url_segments = explode("/", $url); 
$last_segment = array_pop($url_segments); 

list($id) = explode("-", $last_segment); 

echo $id; // Prints 12345 
+0

實際上,運行速度並不快,那麼ircmaxell提供的代碼片段(至少不是可測量的數量)。在我的測試過程中,有時候你的片段,有時候ircmaxell的片段會更快。儘管如此,我的片段幾乎快了一倍。 – yankee 2011-02-07 20:23:05

+0

@yankee,感謝您爲測試和分享結果所做的努力! – 2011-02-07 20:26:50

0

太慢了,我是^^。 好吧,如果你不停留在的preg_match是,這裏是一個快速和可讀性的選擇:

$num = (int)substr($url, strlen($beg)); 

(看你的代碼,我猜,你正在尋找的號碼是數字ID是它是典型的看起來像這樣的網址,不會是「12abc」或其他任何東西。)

相關問題