Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace YouTube URL in text with its HTML embed code

Tags:

regex

php

This function embed youtube videos if found in a string.

My question is what would be the easiest way to only capture the embedded video (the iframe and only the first if there are more) and ignore rest of the string.

function youtube($string,$autoplay=0,$width=480,$height=390)
{
preg_match('#(v\/|watch\?v=)([\w\-]+)#', $string, $match);
  return preg_replace(
    '#((http://)?(www.)?youtube\.com/watch\?[=a-z0-9&_;-]+)#i',
    "<div align=\"center\"><iframe title=\"YouTube video player\" width=\"$width\" height=\"$height\" src=\"http://www.youtube.com/embed/$match[2]?autoplay=$autoplay\" frameborder=\"0\" allowfullscreen></iframe></div>",
    $string);
}
like image 476
domino Avatar asked Nov 19 '11 20:11

domino


1 Answers

Okay, I think I see what you're trying to accomplish. A user inputs a block of text (some comment or whatever), and you find a YouTube URL in that text and replace it with the actual video embed code.

Here's how I've modified it:

function youtube($string,$autoplay=0,$width=480,$height=390)
{
    preg_match('#(?:http://)?(?:www\.)?(?:youtube\.com/(?:v/|watch\?v=)|youtu\.be/)([\w-]+)(?:\S+)?#', $string, $match);
    $embed = <<<YOUTUBE
        <div align="center">
            <iframe title="YouTube video player" width="$width" height="$height" src="http://www.youtube.com/embed/$match[1]?autoplay=$autoplay" frameborder="0" allowfullscreen></iframe>
        </div>
YOUTUBE;

    return str_replace($match[0], $embed, $string);
}

Since you're already locating the URL with the first preg_match(), there's no need to run another regex function for replacing it. Have it match the entire URL, then do a simple str_replace() of your entire match ($match[0]). The video code is captured in the first subpattern ($match[1]). I'm using preg_match() because you only want to match the first URL found. You'd have to use preg_match_all() and modify the code a bit if you wanted to match all URLs, not just the first.

Here's an explanation of my regular expression:

(?:http://)?    # optional protocol, non-capturing
(?:www\.)?      # optional "www.", non-capturing
(?:
                # either "youtube.com/v/XXX" or "youtube.com/watch?v=XXX"
  youtube\.com/(?:v/|watch\?v=)
  |
  youtu\.be/     # or a "youtu.be" shortener URL
)
([\w-]+)        # the video code
(?:\S+)?        # optional non-whitespace characters (other URL params)
like image 61
Wiseguy Avatar answered Oct 19 '22 22:10

Wiseguy