2012-02-25 103 views
0

我需要獲取此iframe代碼的vimeo ID,這是我的字符串。帶有preg_match的PHP正則表達式

$str = '<iframe src="http://player.vimeo.com/video/34134823?title=0&amp;byline=0" width="900" height="506" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>' 

相信ID部分34134823可以是多於或少於8個字符,所以我不能使用索引。
我可以用2次爆炸,一個用於http://player.vimeo.com/video/和一種以上的?問號做到這一點,但我相信這將是一個更好的正則表達式,只有我與一個小白..

回答

1
<?php 
$str = '<iframe src="http://player.vimeo.com/video/34134823?title=0&amp;byline=0" width="900" height="506" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'; 

$stat = preg_match('/.*video\/(\d{1,})\?title.*/', $str, $matches); 

print_r($matches); 
+1

爲什麼'{1,}'? Overy複雜的書寫方式'+'... – 2012-02-25 14:36:44

+0

確實如此。真正。首先想到的東西:) – JTP 2012-02-25 14:40:29

+1

謝謝你,我也將刪除'標題'部分,只是保持'?',這應該是更安全的,如果交換周圍的變量。 – FFish 2012-02-25 14:46:38

2

爲什麼不使用兩個爆炸?當然,你可以用正則表達式來做到這一點。但考慮到URL的定義方式,我會先刪除第一個?之後的所有內容,然後刪除最後的/之前的所有內容。

雖然有些人認爲這裏使用正則表達式優雅(事實上,我甚至可能會自己使用它),strposstrrpos在這裏同樣快速和可靠。

$end = strpos($test, "?") - 1; 
$sta = strrpos(substr($test, 0, $end), "/") + 1; 
$ret = substr($test, $sta, $end); 
+0

超過謝謝你的提示確定。什麼是差異。在'strpos'&'strrpos'上'爆炸'? – FFish 2012-02-25 14:26:30

+1

http://php.net/manual/en/function.explode.php,http://php.net/manual/en/function.strpos.php和http://php.net/manual/en/function .strrpos.php很樂意告訴你這一點。 – Anton 2012-02-25 14:32:25

+1

'爆炸'更昂貴,當你實際上只對線路的一部分感興趣時。使用'strpos'找到'?',然後'strrpos'找到最後的'/',然後'substr'來獲得你需要的字符。簡單而高效。 – 2012-02-25 14:35:58

1
$pattern = '/\<iframe\s+.*src\=\"?[^\"]*player\.vimeo\.com\/video\/([\d]{5,})\??.*\".*\<\/iframe\>/i'; 

if(preg_match($pattern, $iframe_tag, $result)){ 
    $vimeo_id = $result[1]; 
}