1

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!

user998163
  • 461
  • 8
  • 23

3 Answers3

6

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
)
Avinash Raj
  • 160,498
  • 22
  • 182
  • 229
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);
vks
  • 63,206
  • 9
  • 78
  • 110
0

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 
)
Get Off My Lawn
  • 27,770
  • 29
  • 134
  • 260