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.
If there is anyone who is still looking for a better straight up solution , here it is I just played with your code until it gave me an easy solution.
$search = '/www.youtube\.com\/watch\?v=([a-zA-Z0-9]+)/smi';
$replace = "<iframe width='560' height='315' src='https://youtube.com/embed/$1' frameborder='0' allowfullscreen></iframe> ";
$content = preg_replace($search,$replace,$string);
NOTE: to choose how you want the links to be processed just edit the
$search
part, if you will be processing from www.youtube.com it will be$search = '/www.youtube\.com\/watch\?v=([a-zA-Z0-9]+)/smi';
else if you want it to process just youtube.com links just remove the
www. $search = '/youtube\.com\/watch\?v=([a-zA-Z0-9]+)/smi';
here is a function i wrote that you echo out the result:
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:
Either change
$string = 'http://www.youtube.com/watch?v=CfDQ92vOfdc';
to
$string = '<a href="http://www.youtube.com/watch?v=CfDQ92vOfdc" ></a>';
OR
to