change youtube url to embed url in php

2019-04-12 02:11发布

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.

4条回答
欢心
2楼-- · 2019-04-12 02:33

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.

$string     = $content;

$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';

查看更多
Summer. ? 凉城
3楼-- · 2019-04-12 02:47

here is a function i wrote that you echo out the result:

function youtube_url_to_embed($youtube_url) {
    $search = '/youtube\.com\/watch\?v=([a-zA-Z0-9]+)/smi';
    $replace = "youtube.com/embed/$1";
    $embed_url = preg_replace($search,$replace,$youtube_url);
    return $embed_url;
}
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-04-12 02:53

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;
查看更多
Fickle 薄情
5楼-- · 2019-04-12 02:55

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';
查看更多
登录 后发表回答