Search code examples
regexyoutube

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

Solution

  • 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_-]+)?/