change youtube url to embed url in php

php, preg-replace, regex, youtube

Solution

Either change

`$string = 'http://www.youtube.com/watch?v=CfDQ92vOfdc';`

to

`$string = '<a href="http://www.youtube.com/watch?v=CfDQ92vOfdc" ></a>';`

OR

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

to

$search     = '#(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*#x';

Problem

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.

Original source

Related problems