views:

283

answers:

3

How can convert the below youtube urls

$url1 = http://www.youtube.com/watch?v=136pEZcb1Y0&feature=fvhl
$url2 = http://www.youtube.com/watch?feature=fvhl&v=136pEZcb1Y0

into

 $url_embedded = http://www.youtube.com/v/136pEZcb1Y0

using Regular Expressions?

+1  A: 

add the string "http://www.youtube.com/watch/" to the result of applying the regex "v=(\w+)" to the url(s) should do the job.

\w specifies alphanumeric characters (a-z, A-Z, 0-9 and _) and will thus stop at the &

EDIT for updated question. My approach seems a little hackish.

so get the result of applying the regex "v=(\w+)" and then apply the regex "(\w+)" to it. Then prefix it with the string "http://www.youtube.com/v/".

so to sum up:

"http://www.youtube.com/v/" + ( result of "(\w+)" applies to the result of ( "v=(\w+)" applied to the origional url ) )

EDITED AGAIN this approach assumes you are using a regex function that matches a substring instead of the whole string

Also, MvanGeest's version is superior to mine.

suicideducky
Please see the updated question, need output like http://www.youtube.com/v/136pEZcb1Y0
Mithun P
Just extract the parenthesized group and add it to the string "http://www.youtube.com/v/"
Christian Kjær
Isn't that what's in my answer?
MvanGeest
+2  A: 

suicideducky's answer is fine, but you changed the requirements. Try

preg_match($url1, "/v=(\w+)/", $matches);
$url_embedded = "http://www.youtube.com/v/" . $matches[1];

In case the wrong version was still cached, I meant $matches[1]!

MvanGeest
Correct me if I am wrong, but will that not just find the second match of "v=(\w+)" and ad it to youtube.com/v/ ?
suicideducky
The first match, as `$matches[0]` contains the whole matched text. `$matches[1]` contains the video ID because that's what's captured in the parentheses.
MvanGeest
+1 Entirely forgot about groupings behavior.I also edited and posted before I realised another had replies, so sorry about that.
suicideducky
+4  A: 

Here's an example solution:

PHP:

preg_replace('/.+(\?|&)v=([a-zA-Z0-9]+).*/', 'http://youtube.com/watch?v=$2', 'http://www.youtube.com/watch?v=136pEZcb1Y0&feature=fvhl');

Match:

^.+(\?|&)v=([a-zA-Z0-9]+).*$

Replace with:

http://youtube.com/watch?v=$2

Here's how it works: regex analyzer.

mqchen
+1 for most simple (=shortest) and elegant solution
MvanGeest
+1 for single liner
suicideducky