user990583
user990583

Reputation:

preg_replace youtube links - iframe embed

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!

Upvotes: 0

Views: 4032

Answers (2)

Wh1T3h4Ck5
Wh1T3h4Ck5

Reputation: 8509

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.

Upvotes: 0

anubhava
anubhava

Reputation: 786329

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>"

Upvotes: 4

Related Questions