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.
views:
84answers:
3
+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
2009-09-01 11:47:37
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
2009-09-01 11:52:14
@Dav: Yes I know that. But do you know that `.` is a meta character and represents any arbitrary character?
Gumbo
2009-09-01 11:57:13
+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
2009-09-01 11:48:24
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
2009-09-01 11:49:34