Regex to find Youtube Link in string [duplicate]

China☆狼群 提交于 2019-12-06 14:35:48

This would work for you,

\S*\bwww\.youtube\.com\S*

\S* matches zero or more non-space characters.

Code would be,

preg_match('~\S*\bwww\.youtube\.com\S*~', $str, $matches);

DEMO

And i made Some corrections to your original regex.

(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch\?v=)?([^\s]+)

DEMO

$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard  dummy text ever since the 1500s, https://www.youtube.com/watch?v=7TL02DA5MZM when an unknown printer took a galley of type and scrambled it to make a type";
preg_match('~(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch\?v=)?([^\s]+)~', $str, $match);
print_r($match);

Output:

Array
(
    [0] => https://www.youtube.com/watch?v=7TL02DA5MZM
    [1] => 7TL02DA5MZM
)
(?:https?:\/\/)?www\.youtube\.com\S+?v=\K\S+

You can get video id by matching youtube url and then discarding using \K.See demo.

https://regex101.com/r/tX2bH4/21

$re = "/(?:https?:\\/\\/)?www\\.youtube\\.com\\S+?v=\\K\\S+/i";
$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, https://www.youtube.com/watch?v=7TL02DA5MZM when an unknown printer took a galley of type and scrambled it to make a type";

preg_match_all($re, $str, $matches);

I have come up with the following regexp:

https?:\/\/(w{3}\.)?youtube\.com\/watch\?.+?(\s|$)

Here is how I am using this:

$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard  dummy text ever since the 1500s, https://www.youtube.com/watch?v=7TL02DA5MZM when an unknown printer took a galley of type and scrambled it to make a type";

preg_match("/https?:\/\/(w{3}\.)?youtube\.com\/watch\?.+?(\s|$)/", $str, $matches);

$ytube = $matches[0];
$parse = parse_url($ytube);
parse_str($parse["query"], $query);

echo $ytube;
print_r($parse);
print_r($query);

And here is the output of the items:

https://www.youtube.com/watch?v=7TL02DA5MZM
Array
(
    [scheme] => https
    [host] => www.youtube.com
    [path] => /watch
    [query] => v=7TL02DA5MZM 
)
Array
(
    [v] => 7TL02DA5MZM 
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!