正则表达式来查找 youtube url,去掉参数并返回干净的视频 url?

问题描述 投票:0回答:5

想象一下这个网址:

http://www.youtube.com/watch?v=6n8PGnc_cV4&feature=rec-LGOUT-real_rn-2r-13-HM

执行以下操作的最干净、最好的正则表达式是什么:

1.) 我想去掉视频 URL 之后的所有内容。这样就只剩下 http://www.youtube.com/watch?v=6n8PGnc_cV4 了。

2.) 我想将此网址转换为 http://www.youtube.com/v/6n8PGnc_cV4

因为我不太擅长正则表达式,所以我需要你的帮助:

$content = preg_replace('http://.*?\?v=[^&]*', '', $content); 

return $content;

编辑:看看这个!我想创建一个非常简单的 WordPress 插件,它只识别我的 $content 中的每个正常的 YouTube URL 并将其替换为嵌入代码:

<?php
function videoplayer($content) {
    
    $embedcode = '<object class="video" width="308" height="100"><embed src="' . . '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="308" height="100" wmode="opaque"></embed></object>';
    
    //filter normal youtube url like http://www.youtube.com/watch?v=6n8PGnc_cV4&feature=rec-LGOUT-real_rn-2r-13-HM
    //convert it to http://www.youtube.com/v/6n8PGnc_cV4
    //use embedcode and pass along the new youtube url
    $content = preg_replace('', '', $content); 
    
    //return embedcode
    return $content;
}

add_filter('the_content', 'videoplayer');  
?>
regex youtube
5个回答
0
投票

我在我的脚本中使用此搜索条件:

/((http|ftp)\:\/\/)?([w]{3}\.)?(youtube\.)([a-z]{2,4})(\/watch\?v=)([a-zA-Z0-9_-]+)(\&feature=)?([a-zA-Z0-9_-]+)?/

0
投票

您可以将其拆分在第一个&符号上。

$content = explode('&', $content);
$content = $content[0];

0
投票

编辑:最简单的正则表达式:

/http:\/\/www\.youtube\.com\/watch\?v=.*/

Youtube 链接都是一样的。要从中获取视频 ID,首先要从末尾切掉多余的参数,然后切掉除最后 11 个字符之外的所有内容。看看它的实际效果:

$url = "http://www.youtube.com/watch?v=1rnfE4eo1bY&feature=...";
$url = $url.left(42); // "http://www.youtube.com/watch?v=1rnfE4eo1bY"
$url = $url.right(11); // "1rnfE4eo1bY"
$result = "http://www.youtube.com/v/" + $url; // "http://www.youtube.com/v/1rnfE4eo1bY"

您可以使用 Greasemonkey 脚本统一所有 YouTube 链接(通过删除无用的参数):http://userscripts.org/scripts/show/86758。 Greasemonkey 脚本在 Google Chrome 中作为插件本身受支持。

作为奖励,这里有一个(好吧,实际上是两个)内衬:

$url = "http://www.youtube.com/watch?v=1rnfE4eo1bY&feature=...";
$result = "http://www.youtube.com/v/" + $url.left(42).right(11);

--3ICE


0
投票

对于从 Google 搜索 结果页面获取 YouTube 视频 URL 的人来说,模式会略有不同。这些 URL 相当长,而且从视觉上看不出来哪一部分是相关的。

首先,删除与此正则表达式匹配的部分:

(https:\/\/www.google.com\/url?(.)*watch%3Fv%3D)|&usg=(.)*

然后,添加这个字符串:

https://www.youtube.com/watch?v=

您可以使用 RegExr 测试结果。

我只是想分享一个解决方案,因为我只是为了自己的目的而经历了这个过程。我不能保证这适用于所有 URL。


-1
投票
$url = "http://www.youtube.com/v/6n8PGnc_cV4";
$start = strpos($url,"v=");
echo 'http://www.youtube.com/v/'.substr($url,$start+2);
© www.soinside.com 2019 - 2024. All rights reserved.