正则表达式以字符串形式找到Youtube链接

use*_*163 1 php regex preg-match

我有一个像这样的字符串:

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
Run Code Online (Sandbox Code Playgroud)

这就是我所拥有的:

preg_match("(?:http://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch\?)?([^\s]+?)", $content, $m);
    var_dump( $m );
Run Code Online (Sandbox Code Playgroud)

并希望从中提取YouTube链接。视频ID也可以。

谢谢您的帮助!

Avi*_*Raj 5

这将为您工作,

\S*\bwww\.youtube\.com\S*
Run Code Online (Sandbox Code Playgroud)

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

代码是

preg_match('~\S*\bwww\.youtube\.com\S*~', $str, $matches);
Run Code Online (Sandbox Code Playgroud)

演示

我对您的原始正则表达式做了一些更正。

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

演示

$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);
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [0] => https://www.youtube.com/watch?v=7TL02DA5MZM
    [1] => 7TL02DA5MZM
)
Run Code Online (Sandbox Code Playgroud)