I'm trying to convert youtube video links into iframes to embed them onto my website but I'm having a problem as I am already converting urls to anchor tags and it's conflicting with the youtube url.
Here is my code:
$string = 'https://www.google.com and https://www.youtube.com/watch?v=umFQckeDwEE';
$url = '~(\s|^)(https?://.+?)(\s|$)~im';
$string = preg_replace($url, '[url=$0]$0[/url]', $string);
$youtubeURL = '/\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i';
$string = preg_replace($youtubeURL, '<iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/$2\" allowfullscreen></iframe>', $string);
The first line gets anything that is just a plain url as I am using BBCode it conflicted with other stuff like the [img]
tag. The $youtubeURL
is to get all youtube links and turn them into iframes but because of the first link conversion it causes an href
to be put in the scr=
.
I managed to fix my problem by swapping my code around so it converts YouTube links first then the other URLs second and changing it a little. New code:
Launching from your previous question, I've developed and tested a complete battery of regular expressions to get you on your way. I will admit that this set of pattern could be refined further to be more condensed (fewere total patterns) and that the youtube validation patterns could be more strict, but I honestly don't have time to go down those rabbit holes.
When considering the compexity/diversity of youtube urls, you may want to reference this list of examples that I pulled from StackOverflow pages and the internet. https://regex101.com/r/zinjze/1
Code: (Demo)
Unrendered Output: (you can copy-paste my snippet in http://phptester.net/ if you want to see the rendered output)