2015-10-18 146 views
0

我需要僅從URL中提取'id'。網址格式如下。目前,我使用parse_url和substr函數,它工作。然而,如果'id'的長度發生變化,那麼正則表達式就會起作用,這不是一個好的選擇。我不熟悉正則表達式,所以我需要一個想法,以其他方式如何做正則表達式。使用正則表達式從URL中檢索'id'

$url = 'http://www.example.com/stock-footage/53833534/portrait-lifestyle-leisure-caucasian-parents-children-snow-v.html'; 
$URLParts = parse_url($url); 
// echo $URLParts['path']; 
$substring = substr($URLParts['path'],15,8); 
echo $substring; 
+1

您有什麼問題與'parse_url()'.. ..'如果'id'的長度發生變化,這不是一個好的選擇'你究竟是什麼意思? id的長度與parse_url()....的工作完全無關,看着你的代碼,它不是parse_url()那是你的問題,但substr() –

回答

2

您可以使用下面的正則表達式:

preg_match("/.+\/([0-9]+).+/", $url, $matches); 
echo $matches[1]; 

live example

+0

我已經選擇了你的解決方案作爲我的答案。謝謝 –

1

您可以使用此:

<?php 

$url = 'http://www.example.com/stock-footage/53833534/portrait-lifestyle-leisure-caucasian-parents-children-snow-v.html'; 
$URLParts = parse_url($url); 

$exploded = explode('/',$URLParts['path']); 

echo $exploded[2]; 

?> 
+0

我已經投票給你了。無論如何,我正在使用你的解決方案,儘管我的第一選擇是使用正則表達式。 –