Reputation:
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&feature=g-all-u&context=G2f50f6aFAAAAAAAADAA" target="_blank" rel="nofollow">http://www.youtube.com/watch?v=XA5Qf8VHh9I&feature=g-all-u&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>&feature=g-all-u&context=G2f50f6aFAAAAAAAADAA</a>
How can I get rid of the remaining:
&feature=g-all-u&context=G2f50f6aFAAAAAAAADAA</a>
Thnx!
Upvotes: 0
Views: 4032
Reputation: 8509
if you're sure that YouTube link is valid you can just use simple form
$search = '/^.*?v=(\w*?)&.*$/';
with replacement $1
.
Or add .*$
at the end of your pattern to mark everything until the end of subject string.
Upvotes: 0
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&feature=g-all-u&context=G2f50f6aFAAAAAAAADAA" target="_blank" rel="nofollow">http://www.youtube.com/watch?v=XA5Qf8VHh9I&feature=g-all-u&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