开发者

Pulling Variable from variable in URL stored in DB

If $youtu开发者_Python百科beurl = http://www.youtube.com/watch?v=ytWAw6YqN10S

How do I create a "v" variable and have it extract it from $youtubeurl

Example: I have the youtube url stored in the DB but when I am embedding the player the URL needs to be formatted like

www.youtube.com/v/ytWAw6YqN10?fs=1


The cleanest way is to use parse_url() to extract the query string, and parse_str() to fetch the v variable from it.

$youtubeurl = "http://www.youtube.com/watch?v=ytWAw6YqN10S";
$values = array();

$query_string = parse_url($youtubeurl, PHP_URL_QUERY); // extract query string

parse_str($query_string, $values); // turn query string into associative array

echo $values["v"]; // will echo "ytWAw6YqN10S" 


You can use regular-expressions like:

preg_match_all("/^http://www.youtube.com/watch\?v=(.*).*/", $youtubeurl, $matches);

where $matches will be an array containing the matches within () i.e. variable v.

I am not sure about the expression I have given, but I am sure that this idea will work.


 $youtubeurl = "http://www.youtube.com/watch?v=ytWAw6YqN10S";
 $pos = strpos($youtubeurl, "?v=");
 $v = "";
 if($pos !== FALSE)
 {
     $v = substr($youtubeurl, $pos + 3);
 }

 // now $v should contain the value you needed provided the url was valid
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜