将youtube网址转换为iframe嵌入代码无法正常工作(preg_replace)

时间:2015-02-26 22:46:04

标签: php regex

将youtube网址转换为iframe嵌入代码时遇到问题。只有在youtube链接之前有一些文本并且只有1个视频时,它才能正常工作。

代码:

$search = '@[^"\'](?:https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=))([\w\-]{8,25})(?:[&\w-=%]*)\b@xsi';
$replace = '<iframe title="$1" class="youtube" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
$message = preg_replace($search, $replace, $message);

示例1 - 这没关系(一行中没有换行符)

文本:

text http://www.youtube.com/watch?v=4wDOjZvoRLQ text

结果:

text<iframe title="4wDOjZvoRLQ" class="youtube" src="http://www.youtube.com/embed/4wDOjZvoRLQ" frameborder="0" allowfullscreen></iframe> text 

示例2 - 不行。当我在文本中添加换行符时,由于某种原因,结果会在<br /之前包含未关闭的<iframe>标记。

文本:

text
http://www.youtube.com/watch?v=4wDOjZvoRLQ
text

结果:

text <br /<iframe title="4wDOjZvoRLQ" class="youtube" src="http://www.youtube.com/embed/4wDOjZvoRLQ" frameborder="0" allowfullscreen></iframe> <br />text

示例3 - 不行。只有2个没有任何文字的YouTube网址。出于某种原因,结果在http:/

之前包含“<iframe>

文本:

http://www.youtube.com/watch?v=4wDOjZvoRLQ
http://www.youtube.com/watch?v=4wDOjZvoRL

结果:

http:/<iframe title="4wDOjZvoRLQ" class="youtube" src="http://www.youtube.com/embed/4wDOjZvoRLQ" frameborder="0" allowfullscreen></iframe> <br /<iframe title="4wDOjZvoRLQ" class="youtube" src="http://www.youtube.com/embed/4wDOjZvoRLQ" frameborder="0" allowfullscreen></iframe>

1 个答案:

答案 0 :(得分:0)

$reg_exUrl_youtube = "/(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'> \r\n]+)(?![^<]*>)/";
$articleText = "text goes here"
  if ( preg_match($reg_exUrl_youtube, $articleText, $youtubeUrlData) ) {
    $articleText = preg_replace($reg_exUrl_youtube, "<div class=\"video-container\"><iframe src=\"http://www.youtube.com/embed/{$youtubeUrlData[1]}\" allowFullScreen frameborder=\"0\"width=\"560\" height=\"315\"></iframe></div>", $articleText);
  }

这可以解决您的问题吗? $ reg_exUrl_youtube将preg_match $ articleText中的所有youtube链接,并将其替换为嵌入代码,并像以前一样输出$ articleText并替换所有网址。

这不包括在代码中找到的youtube链接(例如<a href="http://youtube.com">)如果您希望pregmatch执行此操作,请将正则表达式更改为:

$reg_exUrl_youtube = "/(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'> \r\n]+)/";

有用的正则表达式测试器: https://regex101.com/