PHP-将Youtube URL转换为嵌入URL
我正在尝试使用以下功能将标准Youtube URL转换为嵌入URL:PHP-将Youtube URL转换为嵌入URL,php,regex,youtube,Php,Regex,Youtube,我正在尝试使用以下功能将标准Youtube URL转换为嵌入URL: <?php $url = 'https://www.youtube.com/watch?v=oVT78QcRQtU'; function getYoutubeEmbedUrl($url) { $shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_]+)\??/i'; $longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((
<?php
$url = 'https://www.youtube.com/watch?v=oVT78QcRQtU';
function getYoutubeEmbedUrl($url)
{
$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_]+)\??/i';
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))(\w+)/i';
if (preg_match($longUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
if (preg_match($shortUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
return 'https://www.youtube.com/embed/' . $youtube_id ;
}
getYoutubeEmbedUrl();
我不明白为什么我的论点太少,而我只有一个论点,我提供了它
如果在PHP中定义函数,则非全局变量在函数中不可访问 因此,必须将URL作为函数的参数提供(定义为
$URL
)
工作解决方案:
<?php
function getYoutubeEmbedUrl($url){
$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_]+)\??/i';
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))(\w+)/i';
if (preg_match($longUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
if (preg_match($shortUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
return 'https://www.youtube.com/embed/' . $youtube_id ;
}
$url = 'https://www.youtube.com/watch?v=oVT78QcRQtU';
$embeded_url = getYoutubeEmbedUrl($url);
echo $embeded_url;
我认为在最后一行执行函数“getYoutubeEmbedUrl()”时没有传递参数
试试“echo getYoutubeEmbedUrl($url);”太好了,谢谢您的解释。到时候我会接受这个答案。短url正则表达式不会捕获所有youtube url,因为有些url中有破折号,正则表达式会将其截断。这里有一个使用破折号的固定正则表达式:$shortUrlRegex='/youtu.be\/([a-zA-Z0-9\-]+)\??/i';
<?php
function getYoutubeEmbedUrl($url){
$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_]+)\??/i';
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))(\w+)/i';
if (preg_match($longUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
if (preg_match($shortUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
return 'https://www.youtube.com/embed/' . $youtube_id ;
}
$url = 'https://www.youtube.com/watch?v=oVT78QcRQtU';
$embeded_url = getYoutubeEmbedUrl($url);
echo $embeded_url;