Johan
Johan

Reputation: 19072

Change url-string

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.

Upvotes: 0

Views: 426

Answers (3)

Amber
Amber

Reputation: 526733

$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);

Upvotes: 1

Alix Axel
Alix Axel

Reputation: 154563

$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];

Upvotes: 0

Gumbo
Gumbo

Reputation: 655319

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];

Upvotes: 3

Related Questions