1

我想从嵌入代码中获取 Youtube URL 的最后一部分,例如:

<iframe width="420" height="315" src="http://www.youtube.com/embed/gaDa2Zgtqo" frameborder="0" allowfullscreen></iframe>

我想要得到的部分是gaDa2Zgtqo

我尝试过使用爆炸,例如

$string = '<iframe width="420" height="315" src="http://www.youtube.com/embed/gaDa2Zgtqo" frameborder="0" allowfullscreen></iframe>'
$exploded = explode('/', $string);
echo $exploded[2]

但这只会导致结果www.youtube.com

我可以使用另一种方法吗?

4

4 回答 4

2

var_dump($exploded);为您提供以下信息:

array (size=6)
  0 => string '<iframe width="420" height="315" src="http:' (length=43)
  1 => string '' (length=0)
  2 => string 'www.youtube.com' (length=15)
  3 => string 'embed' (length=5)
  4 => string 'gaDa2Zgtqo" frameborder="0" allowfullscreen><' (length=45)
  5 => string 'iframe>' (length=7)

所以我们看到必要的字符串在数组的第 5 个元素中。我们需要它的前 10 个字符。

echo substr($exploded[4], 0, 10);
// gaDa2Zgtqo
于 2013-04-28T19:21:33.737 回答
2

你可以试试正则表达式

$str = '<iframe width="420" height="315" src="http://www.youtube.com/embed/gaDa2Zgtqo" frameborder="0" allowfullscreen></iframe>';
preg_match_all('/src="[^"]+?\/([^\/"]+)"/', $str, $x);
var_dump($x);

它会输出

Array
(
    [0] => Array
        (
            [0] => src="http://www.youtube.com/embed/gaDa2Zgtqo"
        )

    [1] => Array
        (
            [0] => gaDa2Zgtqo
        )
)  

所以你想要的字符串在$x[1][0]

如果您在 HTML 字符串中有其他元素具有 src 属性,例如,<img>那么您可以使用以下正则表达式

preg_match_all('/<iframe[^>]+src="[^"]+?\/([^\/"]+)"/', $str, $x);
于 2013-04-28T19:24:50.220 回答
1

如果 URL 格式总是这样,那么为什么不使用:

$string = '<iframe width="420" height="315" src="http://www.youtube.com/embed/gaDa2Zgtqo" frameborder="0" allowfullscreen></iframe>';
preg_match("/embed\/([a-zA-Z0-9\-]+)/", $string, $matches);
$id = $matches[1];
//$id = gaDa2Zgtqo
于 2013-04-28T19:28:28.880 回答
1

用这个:

$string = '<iframe width="420" height="315" src="http://www.youtube.com/embed/gaDa2Zgtqo" frameborder="0" allowfullscreen></iframe>';
preg_match('/(?<=\/embed\/)[^"\']*/', $string,$matches);
echo $matches[0];
于 2013-04-28T19:31:58.610 回答