2016-05-04 22 views
2

我想要使用正則表達式來獲取所有YouTube iframe,並且想要爲找到的每個記錄添加特定的標記。如何使用正則表達式從HTML獲取所有YouTube iframe

例如<youtube-frame></youtube-frame>以iframe begeing和結束。

所需輸出:

<youtube-frame><iframe width="560" height="315" src="https://www.youtube.com/embed/vakfMRyjulw" frameborder="0" allowfullscreen></iframe></youtube-frame> 

<youtube-frame><iframe width="560" height="315" src="https://www.youtube.com/embed/aDGWMlKPKDs" frameborder="0" allowfullscreen></iframe></youtube-frame> 

我的代碼

$embed = ' 
<iframe width="560" height="315" src="https://www.youtube.com/embed/vakfMRyjulw" frameborder="0" allowfullscreen></iframe> 

<iframe width="600" height="350" src="https://tune.pk/player/embed_player.php?vid=6508414&folderp2016/05/04/&width=600&height=350&autoplay=no" frameborder="0" allowfullscreen scrolling="no"></iframe> 

<iframe width="560" height="315" src="https://www.youtube.com/embed/aDGWMlKPKDs" frameborder="0" allowfullscreen></iframe> 

<iframe width="600" height="350" src="https://tune.pk/player/embed_player.php?vid=6508414&folder=2016/05/04/&width=600&height=350&autoplay=no" frameborder="0" allowfullscreen scrolling="no"></iframe> 

<iframe width="600" height="350" src="https://tune.pk/player/embed_player.php?vid=6508414&folder=2016/05/04/&width=600&height=350&autoplay=no" frameborder="0" allowfullscreen scrolling="no"></iframe> 
'; 

我已經試過?

$pattern = '/<iframe\.*src=\"//youtube"\.*/'; 
$iframeSrc = preg_match($pattern, $embed, $matches); 
var_dump($iframeSrc); 
+0

Error_reporting不適合你嗎?你爲什麼認爲'src = \「// youtube」'會匹配'src =「https:// www.youtube。...'? – mario

+0

我已經回答了,但仍然是:在你的問題下會缺少什麼」已嘗試?「是您嘗試的代碼的結果(例如'var_dump'的輸出)。 – CherryDT

回答

3

試試這個:

$iframeSrc = preg_replace('/<iframe[^>]*src\s*=\s*"?https?:\/\/[^\s"\/]*youtube.com(?:\/[^\s"]*)?"?[^>]*>.*?<\/iframe>/gi', '<youtube-frame>$0</youtube-frame>', $embed); 

它使用preg_replace和全球正則表達式與<youtube-frame>$0</youtube-frame>替換所有的YouTube的IFrame標記(包括其關閉標籤),其中$0是原始的字符串。

如果您完全確定輸入的格式,理論上可以簡化正則表達式,但是我將其設計爲足夠強大,以適應當前被瀏覽器接受的其他語法,如src=http://example.comsrc = "http://example.com"等,以及它只匹配*.youtube.com域名的來源,而不是像myyoutubesite.com

+0

謝謝@CherryDT請你解釋一下'gi'do'<\/iframe>/gi' – Hassaan

+1

'g'使它成爲全局的所以它匹配多次(否則它只匹配一次加任何submatches),'i'使它不區分大小寫,因爲'