How to replace Youtube urls in text using inline code (in PHP)?

This is what I have so far:

<?php $content = "word1 http://www.youtube.com/watch?v=yqfKe-67foQ&feature=related word2 http://www.youtube.com/watch?v=2vq7gDEn99Y&feature=related word3 http://www.youtube.com/watch?v=nW5HxgMYRto\nhttp://www.youtube.com/watch?v=8Uc2lpH0iZ0&feature=fvhl"; $pattern = '/http:\/\/www\.youtube\.com\/watch\?(.*)v=([a-zA-Z0-9_\-]+)(\S*)/i'; $replace = '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/$2&amp;hl=en_US&amp;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/$2&amp;hl=en_US&amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>'; $content = preg_replace($pattern, $replace, $content); echo $content; ?> 

I honestly have no idea why this is not working. Some help would be appreciated. Thanks.

+1
source share
3 answers

You just need to make * inanimate:

 http:\/\/www\.youtube\.com\/watch\?(.*?)v=([a-zA-Z0-9_\-]+)(\S*) 

See "Watch out for greed . "

+1
source

Try this simple function to replace urls

 function youtube($string) { return preg_replace( '#(http://(www.)?youtube.com)?/(v/|watch\?v\=)([-|~_0-9A-Za-z]+)&?.*?#i', '<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/$4" frameborder="0" allowfullscreen></iframe>', $string ); } echo youtube('http://www.youtube.com/watch?v=VWsjWCt1PsQ'); echo youtube('http://youtube.com/watch?v=VWsjWCt1PsQ'); echo youtube('http://youtube.com/v/VWsjWCt1PsQ'); echo youtube('http://www.youtube.com/v/VWsjWCt1PsQ'); 
+1
source

I would just create a line with customized paste code. Link attribute can be #LINK# , width="#WIDTH#" . Then replace all parameters with your own value. It can be much more convenient to use. Or you can just use the youtube embed code generator for this.

0
source

Source: https://habr.com/ru/post/901908/


All Articles