Search code examples
phpstringreplaceyoutubefind

Find youtube Link in PHP string and Convert it into embed code?


Find a Youtube video link in PHP String and convert it into Embed Code?

Embed Code:

<iframe width="420" height="315" src="//www.youtube.com/embed/0GfCP5CWHO0" frameborder="0" allowfullscreen></iframe>

PHP Code / String:

<?php echo $post_details['description']; ?>

Youtube Link:

http://www.youtube.com/watch?v=0GfCP5CWHO0

Solution

  • Try this:

    preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>",$post_details['description']);