1

This is what I've got so far:

<?php

 $content = "word1 http://www.youtube.com/watch?v=yqfKe-67foQ&feature=related word2 http://www.youtube.com/watch?v=2vq7gDEn99Y&feature=related word3 http://www.youtube.com/watch?v=nW5HxgMYRto\nhttp://www.youtube.com/watch?v=8Uc2lpH0iZ0&feature=fvhl";
 $pattern = '/http:\/\/www\.youtube\.com\/watch\?(.*)v=([a-zA-Z0-9_\-]+)(\S*)/i';
 $replace = '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/$2&amp;hl=en_US&amp;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/$2&amp;hl=en_US&amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>';

 $content = preg_replace($pattern, $replace, $content);
 echo $content;

?>

I honestly have no idea why it doesn't work. Some help would be appreciated. Thanks.

1
  • try just filter the video id... Commented Jul 14, 2010 at 10:01

3 Answers 3

1

You just have to make * non-greedy:

http:\/\/www\.youtube\.com\/watch\?(.*?)v=([a-zA-Z0-9_\-]+)(\S*)

See "Watch out for greediness".

Sign up to request clarification or add additional context in comments.

Comments

1

Try this simple function for URL replacement

function youtube($string)
{
  return preg_replace(
    '#(http://(www.)?youtube.com)?/(v/|watch\?v\=)([-|~_0-9A-Za-z]+)&?.*?#i',
    '<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/$4" frameborder="0" allowfullscreen></iframe>',
    $string
  );
}

echo youtube('http://www.youtube.com/watch?v=VWsjWCt1PsQ');
echo youtube('http://youtube.com/watch?v=VWsjWCt1PsQ');
echo youtube('http://youtube.com/v/VWsjWCt1PsQ');
echo youtube('http://www.youtube.com/v/VWsjWCt1PsQ');

Comments

0

I would just create a string with a configured embed code. Link attribute could be #LINK#, width="#WIDTH#". Than replace all parameters with your own value. It could be much more comfortable to use. Or you can simply use a youtube embed code generator for that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.