Regex find Youtube link in line

I have a line like this:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry 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 link to ittube. The video ID will also be fine.

Help does not help!

+1
source share
3 answers

It will work for you

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

\S* matches zero or more characters without a space.

The code will be

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

Demo

And I made some corrections to the 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 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); 

Conclusion:

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

You can get the video id by matching the YouTube URL and then dropping with \K Watch the 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 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
source

I got the following regexp:

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

Here is how I use it:

 $str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry 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 elements:

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

Source: https://habr.com/ru/post/892285/


All Articles