views:

84

answers:

3

I want this url http://www.youtube.com/watch?v=dgNgODPIO0w&feature=rec-HM-fresh+div to be transformed to: http://www.youtube.com/v/dgNgODPIO0w with php.

+3  A: 

I would use a combination of parse_url and parse_str:

$url = 'http://www.youtube.com/watch?v=dgNgODPIO0w&feature=rec-HM-fresh+div';
$parts = parse_url($url);
parse_str($parts['query'], $params);
$url = 'http://www.youtube.com/v/'.$params['v'];

Or a simple regular expression:

preg_match('/^'.preg_quote('http://www.youtube.com/watch?', '/').'(?:[^&]*&)*?v=([^&]+)/', $url, $match);
$url = 'http://www.youtube.com/v/'.$match[1];
Gumbo
You know that you can use a different character instead of / as your delimiter in a regex, right? Whatever the first character of your string is will be treated as a delimiter, so you can use something like # or @ or ~ instead of / (to prevent from having to escape backslashes in the url itself).
Amber
@Dav: Yes I know that. But do you know that `.` is a meta character and represents any arbitrary character?
Gumbo
+1  A: 
$url = 'http://www.youtube.com/watch?v=dgNgODPIO0w&feature=rec-HM-fresh+div';
$url = preg_replace('@http://www.youtube.com/watch\?v=([^&;]+).*?@', 'http://www.youtube.com/v/$1', $url);
Amber
A: 
$url = 'http://www.youtube.com/watch?v=dgNgODPIO0w&feature=rec-HM-fresh+div';

preg_match('~(http://www\.youtube\.com/watch\?v=.+?)&.*?~i', $url, $matches);

echo $matches[1];
Alix Axel