通过preg_replace()交换所有youtube网址以进行嵌入

Axe*_*xel 3 php preg-replace

您好我正在尝试将youtube链接转换为嵌入代码.

这就是我所拥有的:

<?php

$text = $post->text;

     $search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*$#x';
     $replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe></center>';
     $text = preg_replace($search, $replace, $text);


echo $text;
?>
Run Code Online (Sandbox Code Playgroud)

它适用于一个链接.但是,如果我添加两个,它将只交换最后一次出现.我需要改变什么?

Azi*_*ziz 6

你没有正确处理字符串的结尾.取下$,并用结束标签替换它</a>.这将解决它.

 $search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*<\/a>#x';
 $replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe></center>';
 $text = preg_replace($search, $replace, $text);
Run Code Online (Sandbox Code Playgroud)