开发者

Regexp to find youtube url, strip off parameters and return clean video url?

imagine this url:

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

what is the cleanest and best regexp to do the following:

1.) i want to strip off every thing after the video URL. so that only http://www.youtube.com/watch?v=6n8PGnc_cV4 remains.

2.) i want to convert this url into http://www.youtube.com/v/6n8PGnc_cV4

Since i'm not much of a regexp-ert i need your help:

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

return $content;

edit: check this out! I want to create a really simple WordPress plugin that just recognizes every normal youtube URL in my $content and replaces it with the embed code:

<?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');  
?>


I use this search criteria in my script:

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


You could just split it on the first ampersand.

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


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

Youtube links are all the same. To get the video id from them, first you slice off the extra parameters from the end and then slice off everything but the last 11 characters. See it in action:

$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"

You can uniformize all your youtube links (by removing useless parameters) with a Greasemonkey script: http://userscripts.org/scripts/show/86758. Greasemonkey scripts are natively supported as addons in Google Chrome.

And as a bonus, here is a one (okay, actually two) liner:

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

--3ICE


$url = "http://www.youtube.com/v/6n8PGnc_cV4";
$start = strpos($url,"v=");
echo 'http://www.youtube.com/v/'.substr($url,$start+2);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜