Replace the YouTube URL in the text with HTML code

This function inserts youtube videos if they can be found in the line.

My question is the easiest way to capture the embedded video (iframe and only the first if there is more) and ignore the rest of the line.

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); } 
+6
source share
1 answer

Well, I think I see what you are trying to achieve. A user enters a block of text (some comment or something else), and you find the YouTube URL in that text and replace it with the actual embed code for the video.

Here's how I changed 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 already find the url with the first preg_match() , there is no need to run another regular expression function to replace it. Match the entire URL, then do a simple str_replace() for your entire match ( $match[0] ). The video code is fixed in the first subpattern ( $match[1] ). I use preg_match() because you only want to match the first URL found. You will need to use preg_match_all() and change the code a bit if you want to combine all the URLs, not just the first ones.

Here is an explanation of my regex:

 (?: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) 
+13
source

Source: https://habr.com/ru/post/901907/


All Articles