我想使用regex获取所有YouTube iframe
,并想为找到的每个记录添加特定的标记。
例如<youtube-frame></youtube-frame>
到iframe begining和end。
所需输出:
<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);
试试这个:
$iframeSrc = preg_replace('/<iframe[^>]*src's*='s*"?https?:'/'/[^'s"'/]*youtube.com(?:'/[^'s"]*)?"?[^>]*>.*?<'/iframe>/i', '<youtube-frame>$0</youtube-frame>', $embed);
这使用preg_replace
和全局正则表达式将所有YouTube IFrame标记(包括其结束标记)替换为<youtube-frame>$0</youtube-frame>
,其中$0
是原始字符串。
理论上,如果您完全确定输入的格式,正则表达式可以简化,但我将其设计为足够强大,可以应对当今浏览器所接受的其他语法,如src=http://example.com
或src = "http://example.com"
等,并且它只匹配*.youtube.com
域上的源,而不匹配myyoutubesite.com
。