0

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 3

3

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];
Sign up to request clarification or add additional context in comments.

2 Comments

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).
@Dav: Yes I know that. But do you know that . is a meta character and represents any arbitrary character?
1
$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);

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.