Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change youtube url to embed url in php

I found this code (Swap all youtube urls to embed via preg_replace()) to swap youtube urls (http://www.youtube.com/watch?v=CfDQ92vOfdc, or http://www.youtube.com/v/CfDQ92vOfdc) into youtube embed urls (http://www.youtube.com/embed/CfDQ92vOfdc) but it doesn't seem to be working? Any ideas? I don't know much about regular expression.

Here's the code:

$string     = 'http://www.youtube.com/watch?v=CfDQ92vOfdc';
$search     = '#<a (?:.*?)href=["\\\']http[s]?:\/\/(?:[^\.]+\.)*youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)([\w\-\_]+)["\\\']#ixs';
$replace    = 'http://www.youtube.com/embed/$2';
$url        = preg_replace($search,$replace,$string);

but it's still displaying as:

http://www.youtube.com/watch?v=CfDQ92vOfdc

instead of:

http://www.youtube.com/embed/CfDQ92vOfdc

Thanks in advance.

like image 889
SoulieBaby Avatar asked Dec 06 '22 08:12

SoulieBaby


1 Answers

One problem is that your expression is expecting a-href tags around the address. Another issue is that your $replace string is using single-quotes which will not parse $2.

This simpler expression should work:

$string     = 'http://www.youtube.com/watch?v=CfDQ92vOfdc';
$search     = '/youtube\.com\/watch\?v=([a-zA-Z0-9]+)/smi';
$replace    = "youtube.com/embed/$1";    
$url = preg_replace($search,$replace,$string);
echo $url;
like image 179
Clayton Bell Avatar answered Dec 21 '22 23:12

Clayton Bell