我正在尝试将YouTube链接(包括a标签)替换为iframe嵌入代码。
我到目前为止所得到的:

$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);

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

我如何摆脱剩余的东西:
&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';

测试:
$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);

输出:
string(97) "<iframe width="150" height="84" src="http://www.youtube-nocookie.com/embed/XA5Qf8VHh9I"></iframe>"

关于php - preg_replace YouTube链接-iframe嵌入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9893201/

10-11 03:22