Use parse_url() and parse_str().
(You can use regexes for just about anything, but they are very easy to make an error in, so if there are PHP functions specifically for what you are trying to accomplish, use those.)
parse_url takes a string and cuts it up into an array that has a bunch of info. You can work with this array, or you can specify the one item you want as a second argument. In this case we're interested in the query, which is PHP_URL_QUERY
.
Now we have the query, which is v=C4kxS1ksqtw&feature=relate
, but we only want the part after v=
. For this we turn to parse_str
which basically works like GET
on a string. It takes a string and creates the variables specified in the string. In this case $v
and $feature
is created. We're only interested in $v
.
Putting everything together, we have:
<?php
$url = "http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ) );
echo $v;
// Output: C4kxS1ksqtw
?>
Edit:
hehe - thanks Charles. That made me laugh, I've never seen the Zawinski quote before:
Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.
– Jamie Zawinski