关于如何将YouTube网址转换为嵌入代码的示例很多,但我需要反向代码。我从未成功使用所有这些表达式,所以我的问题是如何将嵌入代码转换为URL ?提前致谢。

最佳答案

在PHP中,您可以使用 DOMDocument 来获取srciframe属性,并使用 preg_replace() 将该属性转换为视频网址:

$embed = '<html><head></head><body><p>Hello, there is the video <iframe width="560" height="315" src="http://www.youtube.com/embed/K75a2k_6QWs" frameborder="0" allowfullscreen></iframe> what do you think?</p></body></html>';

$doc = new DOMDocument();
$doc->loadHTML($embed);

while($iframe = $doc->getElementsByTagName('p')->item(0)->getElementsByTagName('iframe')->item(0)) {
    $url = preg_replace(
        '~/embed/~',
        '/watch?v=',
        $iframe->getAttribute('src')
    );

    $iframe->parentNode->replaceChild(
        $doc->createTextNode($url),
        $iframe
    );
}

echo $result = $doc->getElementsByTagName('p')->item(0)->nodeValue; //'Hello, there is the video http://www.youtube.com/watch?v=K75a2k_6QWs what do you think?'

07-24 09:46
查看更多