Reputation: 21
I need to get a string out of some youtube urls looking like that:
http://www.youtube.com/embed/WJlfVjGt6Hg?list=EC1512BD72E7C9FFCA&hl=en_US
I need to get the variables between"../embed/" and "?list=.." (-> WJlfVjGt6Hg ).
The code for the other youtube urls looks like this:
// Checks for YouTube iframe, the new standard since at least 2011
if ( !isset( $matches[1] ) ) {
preg_match( '#https?://www\.youtube(?:\-nocookie)?\.com/embed/([A-Za-z0-9\-_]+)#', $markup, $matches );}
How can I do that ?
Upvotes: 2
Views: 2072
Reputation: 173542
It's the base name of the path from your url:
$url = 'http://www.youtube.com/embed/WJlfVjGt6Hg?list=EC1512BD72E7C9FFCA&hl=en_US';
echo basename(parse_url($url, PHP_URL_PATH));
// WJlfVjGt6Hg
Upvotes: 3
Reputation: 93636
Don't use a regular expression. Not every problem that involves a string is best solved with regexes.
Use the parse_url()
function, built in to PHP, to break apart the parts for you.
http://php.net/manual/en/function.parse-url.php is the manual page for it. Here's how you use it:
$url = 'http://www.youtube.com/embed/WJlfVjGt6Hg?list=EC1512BD72E7C9FFCA&hl=en_US';
$parts = parse_url( $url );
print_r( $parts );
$path_parts = explode( '/', $parts['path'] );
print_r( $path_parts );
$last_part = $path_parts[count($path_parts)-1];
print "Youtube video ID = $last_part\n";
And when you run that, you get this:
Array
(
[scheme] => http
[host] => www.youtube.com
[path] => /embed/WJlfVjGt6Hg
[query] => list=EC1512BD72E7C9FFCA&hl=en_US
)
Array
(
[0] =>
[1] => embed
[2] => WJlfVjGt6Hg
)
Youtube video ID = WJlfVjGt6Hg
Upvotes: 1
Reputation: 3260
Hi you could use the following regular expression:
/embed\/([^\?]+)/
A short explanation - this matches all characters after 'embed/' that aren't a question mark, until it finds a question mark.
Here's a sample script which shows you the output you're looking for:
<?php
$test="http://www.youtube.com/embed/WJlfVjGt6Hg?list=EC1512BD72E7C9FFCA&hl=en_US";
$matches = array();
preg_match('/embed\/([^\?]+)/', $test, $matches);
print_r($matches);
// The value we're looking for is in index 1 of the array
echo $matches[1];
Output is:
Array
(
[0] => embed/WJlfVjGt6Hg
[1] => WJlfVjGt6Hg
)
WJlfVjGt6Hg
Upvotes: 0