0

I am trying to replace youtube links including the a tags with the iframe embed code. What I got so far:

$tube_link = "<a href="http://www.youtube.com/watch?v=XA5Qf8VHh9I&amp;feature=g-all-u&amp;context=G2f50f6aFAAAAAAAADAA" target="_blank" rel="nofollow">http://www.youtube.com/watch?v=XA5Qf8VHh9I&amp;feature=g-all-u&amp;context=G2f50f6aFAAAAAAAADAA</a>"

$search = '%<a(.*)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v= ))([\w\-]{10,12})(?:)([\w\-]{0})\b%x';

$replace = '<iframe width="150" height="84" src="http://www.youtube-nocookie.com/embed/$2"></iframe>';

$embed_code = preg_replace($search, $replace, $tube_link);

Result:

<iframe src="http://www.youtube-nocookie.com/embed/XA5Qf8VHh9"></iframe>&amp;feature=g-all-u&amp;context=G2f50f6aFAAAAAAAADAA</a>

How can I get rid of the remaining:

&amp;feature=g-all-u&amp;context=G2f50f6aFAAAAAAAADAA</a>

Thnx!

  • Don't use regular expressions to parse HTML. It's ill suited for the task. Use XPath or something similar instead. It will work a lot better. – Till Helge Mar 27 '12 at 16:04

2 Answers2

4

Use this regex:

$search =
 '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=))([\w\-]{10,12}).*$#x';

TESTING:

$tube_link = '<a href="http://www.youtube.com/watch?v=XA5Qf8VHh9I&amp;feature=g-all-u&amp;context=G2f50f6aFAAAAAAAADAA" target="_blank" rel="nofollow">http://www.youtube.com/watch?v=XA5Qf8VHh9I&amp;feature=g-all-u&amp;context=G2f50f6aFAAAAAAAADAA</a>';
$search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=))([\w\-]{10,12}).*$#x';
$replace = '<iframe width="150" height="84" src="http://www.youtube-nocookie.com/embed/$2"></iframe>';
$embed_code = preg_replace($search, $replace, $tube_link);
var_dump($embed_code);

OUTPUT:

string(97) "<iframe width="150" height="84" src="http://www.youtube-nocookie.com/embed/XA5Qf8VHh9I"></iframe>"
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thnx, just what I was looking for. –  Mar 27 '12 at 16:56
  • how would you do this for youtube links that have hashes at the end for timing? E.g: "http://www.youtube.com/watch?v=jECIv7zlD4c&feature=player_embedded#t=30s" – Luc Feb 28 '13 at 11:56
  • @Luc This is very old question, pls post a new one and then I will try to find a suitable answer for you. – anubhava Feb 28 '13 at 12:03
  • thanks @anubhava Please find my post here: http://stackoverflow.com/questions/15147993/youtube-embedded-video-pregreplace-with-start-timing – Luc Feb 28 '13 at 23:56
0

if you're sure that YouTube link is valid you can just use simple form

$search = '/^.*?v=(\w*?)&.*$/';

with replacement $1.

See example here!

Or add .*$ at the end of your pattern to mark everything until the end of subject string.

Wh1T3h4Ck5
  • 8,399
  • 9
  • 59
  • 79
  • Thnx for your reply. Not exactly what I was looking for, but useful none the less. –  Mar 27 '12 at 17:02