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://)?
source share