Replace YouTube URL in text with its HTML embed code

后端 未结 1 649
不知归路
不知归路 2021-01-05 17:56

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 fir

相关标签:
1条回答
  • 2021-01-05 18:32

    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)
    
    0 讨论(0)
提交回复
热议问题