我在将youtube URL转换为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-不正常。当我在文本中添加换行符时,由于某种原因,结果在<iframe>
之前包含未关闭的<br /
标记。
文本:
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 URL没有任何文本。由于某种原因,结果在<iframe>
之前包含"http:/
"
文本:
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>
$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将预匹配$articleText中的所有youtube链接,并将其替换为嵌入代码,并像以前一样输出替换了所有URL的$articleText。
这不包括在标签中找到的youtube链接(例如<a href="http://youtube.com">
)。如果您希望预赛进行此操作,请将正则表达式更改为:
$reg_exUrl_youtube = "/(?:http(?:s)?:'/'/)?(?:www'.)?(?:youtu'.be'/|youtube'.com'/(?:(?:watch)?'?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)'/))([^'?&'"'> 'r'n]+)/";
有用的正则表达式测试程序:https://regex101.com/