2017-04-06 61 views
1
<?php 

function convertYoutube($string) { 
    return preg_replace(
     "/\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i", 
     "<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/$2\" allowfullscreen></iframe>", 
     $string 
    ); 
} 

$text = "Youtube long url: https://www.youtube.com/watch?v=waIkasvAVGo\n\nYoutube short url: http://youtu.be/waIkasvAVGo"; 

echo convertYoutube($text); 

我发现这个代码在这个网站: http://syframework.alwaysdata.net/convert-youtube-url-to-iframe正则表达式 - BB代码才能使用Youtube标签

该脚本工作得很好。但是,只需要在BBcode中工作即可。例如:[YouTube]<url>[/YouTube]

有没有人有如何解决这个问题的建议?

+0

请不要用手做简码,用一个完善的图书馆就像我自己的简码:https://github.com/thunderer/Shortcode –

回答

1

试试这个:

<?php 

    function convertYoutube($string) { 
     return preg_replace(
      "/\[youtube\]\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)\[\/youtube\]/i", 
      "<iframe width='420' height='315' src='//www.youtube.com/embed/$2' allowfullscreen></iframe>", 
      $string 
     ); 
    } 

    $text = "Youtube long url: [youtube]https://www.youtube.com/watch?v=waIkasvAVGo[/youtube]\n\nYoutube short url: [youtube]http://youtu.be/waIkasvAVGo[/youtube]"; 

    echo convertYoutube($text); 
?> 
+0

谢谢。有用 – 3kbest