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

时间:2015-01-15 17:11:12

标签: 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

这就是我所拥有的:

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

并希望从中提取youtube链接。 视频ID也没问题。

非常感谢你的帮助!

3 个答案:

答案 0 :(得分:3)

这对你有用,

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

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

代码将是,

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
)

答案 1 :(得分:2)

(?:https?:\/\/)?www\.youtube\.com\S+?v=\K\S+

您可以通过匹配youtube网址获取视频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);

答案 2 :(得分:0)

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

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 
)