如何从iframe获取id? [英] How to get the id from iframe?

查看:174
本文介绍了如何从iframe获取id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从iframe获取youtube id。并使用此链接进行此链接提供的正则表达式此处

I am tring to get the youtube id from the iframe. And using this link for regular expression given by this link here

我正在使用此代码,但得到数组(0){}结果。这是代码:

I am using this code but getting the array(0){} result. Here is the code:

`

    preg_match('/src="\/\/(?:https?:\/\/)?.*\/(.*?)\?rel=\d*"/',$urldd, $matches);

     var_dump($matches);
        echo $matches[0][0];`

我使用preg_match很差所以任何人都可以帮助我正确地从iframe获取youtube id。

I am poor in using preg_match so please can anyone help me to get the youtube id from iframe properly.

推荐答案

或者,您也可以使用 DOMDocument 获取该特定网址,然后使用 parse_url()。示例代码:

Alternatively, you can also use DOMDocument to get that particular url, then use parse_url(). Sample Code:

$html = '<iframe width="560" height="315" src="//www.youtube.com/embed/0gugBiEkLwU?rel=0" frameborder="0" allowfullscreen></iframe>';
$dom = new DOMDocument();
$dom->loadHTML($html);
$iframe = $dom->getElementsByTagName('iframe');
$url = '';
foreach($iframe as $tag) {
    $url = $tag->getAttribute('src');
}
$output = parse_url($url, PHP_URL_PATH);
$pieces = array_filter(explode('/', $output));
$id = end($pieces);

// Should output 0gugBiEkLwU

如果你坚持使用正则表达式,你可以做这样的事情:

If you insist to use regex, you could do something like this:

$pattern = '#(?<=(?:v|i)=)[a-zA-Z0-9-]+(?=&)|(?<=(?:v|i)\/)[^&\n]+|(?<=embed\/)[^"&\n]+|(?<=‌​(?:v|i)=)[^&\n]+|(?<=youtu.be\/)[^&\n]+#';
$html = '<iframe width="560" height="315" src="//www.youtube.com/embed/0gugBiEkLwU?rel=0" frameborder="0" allowfullscreen></iframe>';
preg_match($pattern, $html, $matches);
$url = reset($matches);
$url = strtok($url, '?');
echo $url; // 0gugBiEkLwU

这篇关于如何从iframe获取id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆