I'm trying to parse youtube link to the video, to insert it into the site.

The code is as follows:

$url = 'http://www.youtube.com/watch?v=jNQXAC9IVRw'; $parsed_url = parse_url($url); parse_str($parsed_url['query'], $parsed_query); echo '<iframe src="http://www.youtube.com/embed/' . $parsed_query['v'] . '" type="text/html" width="400" height="300" frameborder="0"></iframe>'; 

I use it on WordPress. The problem turned out to be that if a link is crammed into $ url, then everything is beautiful. But if I assign the value $ url dynamically from the admin panel, then I get the output of http://www.youtube.com/embed/ without the numerical code of the video.

  • What is the "custom field value"? Please add the transcript directly to the question. - aleksandr barakin
  • @alexanderbarakin edited a post. - wkornilow
  • And you tried to enter in the admin panel not the full address, but only the video code. Those. in your case jNQXAC9IVRw ? Maybe he will be smart and add it to the embed? - cyadvert
  • @cyadvert if you just enter the video code, then this of course makes everything much easier. But not for the user;) It is much more convenient to just copy the link from the address bar and paste it into the appropriate place in the admin panel. That and I do not need WP to automatically insert into the embed. - wkornilow

1 answer 1

Try these regulars

 if ( preg_match( "/(http|https):\/\/(www.youtube|youtube|youtu)\.(be|com)\/([^<\s]*)/", $url, $match ) ) { if ( preg_match( '/youtube\.com\/watch\?v=([^\&\?\/]+)/', $url, $id ) ) { $values = $id[1]; } else if ( preg_match( '/youtube\.com\/embed\/([^\&\?\/]+)/', $url, $id ) ) { $values = $id[1]; } else if ( preg_match( '/youtube\.com\/v\/([^\&\?\/]+)/', $url, $id ) ) { $values = $id[1]; } else if ( preg_match( '/youtu\.be\/([^\&\?\/]+)/', $url, $id ) ) { $values = $id[1]; } else if ( preg_match( '/youtube\.com\/verify_age\?next_url=\/watch%3Fv%3D([^\&\?\/]+)/', $url, $id ) ) { $values = $id[1]; } }