问题
I have a string like that:
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
This is what I have:
preg_match("(?:http://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch\?)?([^\s]+?)", $content, $m);
var_dump( $m );
and want to extract the youtube link form it. The video id, would be okay, too.
Nay help is appreciated!
回答1:
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
)
回答2:
(?: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);
回答3:
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
)
来源:https://stackoverflow.com/questions/27969062/regex-to-find-youtube-link-in-string