在字符串中查找 Youtube Link 的正则表达式

Regex to find Youtube Link in string

我有一个这样的字符串:

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("(?:http://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch\?)?([^\s]+?)", $content, $m);
    var_dump( $m );

并想从中提取 youtube link。 视频id也可以。

非常感谢您的帮助!

这对你有用,

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

\S* 匹配零个或多个非 space 字符。

代码是,

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

DEMO

我对你原来的正则表达式做了一些修正。

(?: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);

输出:

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

您可以通过匹配 youtube url 获取视频 ID,然后使用 \K 丢弃。查看演示。

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);

我想出了以下正则表达式:

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

以下是我的使用方法:

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

这是项目的输出:

https://www.youtube.com/watch?v=7TL02DA5MZM
Array
(
    [scheme] => https
    [host] => www.youtube.com
    [path] => /watch
    [query] => v=7TL02DA5MZM 
)
Array
(
    [v] => 7TL02DA5MZM 
)