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 Answers
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];
2 Comments
Amber
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).
Gumbo
@Dav: Yes I know that. But do you know that
. is a meta character and represents any arbitrary character?