Search code examples
phppreg-replacepreg-replace-callback

Remove additional parameters from Youtube link


I have a function that converts Youtube links into linked youtube thumbnail. I also need to remove additional parameters from Youtube links, for example:

https://www.youtube.com/watch?v=9_pIaI93YGY&list=RD9_pIaI93YGY&start_radio=1

needs to be:

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

This my code:

$message = 'text text text https://www.youtube.com/watch?v=9_pIaI93YGY text text text https://www.youtube.com/watch?v=1PUT2a5NafI&list=RD1PUT2a5NafI&start_radio=1 more text more text';

$reg_exUrl_youtube = "/(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'> \r\n]+)(?![^<]*>)/";

$message = preg_replace_callback($reg_exUrl_youtube, function($matches) {
return "<div class=\"videoss videoss{$matches[1]}\"><a href=\"#\" class=\"videoshow\" id=\"{$matches[1]}\"><div style=\"background:url(/i/play.png) center no-repeat,url([zzzzz]img.youtube.com/vi/{$matches[1]}/mqdefault.jpg) center no-repeat;background-size:30%,cover;\" class=\"pd39 mroim60\"></div></a></div>";
}, $message);

But the result is as you can see in the image below. Additional parameters are not being removed and displayed as text:

enter image description here

So, how do I remove all additional parameters from Youtube links?


Solution

  • Using your pattern you could match all after the capturing group using 0+ times a non whitespace char \S* so that it will not be in the replacement string.

    Regex demo | Php demo

    The id is in group 1 and you can create your custom replacement using $matches[1]

    There can be a few optimizations for your pattern. If you use a different delimiter than / like ~, you don't have to escape the forward slashes.

    These constructs (?:i)? can be simplified to i? and you don't have to escape the ? and " in the character class. If you don't want to match a space or newline, perhaps matching \s in the negated character class could be shorter.

    For example

    $reg_exUrl_youtube = '~(?:https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com/(?:(?:watch)?\?(?:.*&)?vi?=|(?:embed|vi?|user)/))([^?&"\'>\s]+)(?![^<]*>)\S*~';
    $message = 'text text text https://www.youtube.com/watch?v=9_pIaI93YGY text text text https://www.youtube.com/watch?v=1PUT2a5NafI&list=RD1PUT2a5NafI&start_radio=1 more text more text';
    
    $message = preg_replace_callback($reg_exUrl_youtube, function($matches) {
        return "<div class=\"videoss videoss{$matches[1]}\"><a href=\"#\" class=\"videoshow\" id=\"{$matches[1]}\"><div style=\"background:url(/i/play.png) center no-repeat,url([zzzzz]img.youtube.com/vi/{$matches[1]}/mqdefault.jpg) center no-repeat;background-size:30%,cover;\" class=\"pd39 mroim60\"></div></a></div>";
    }, $message);
    
    echo $message;