0

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

could you please update it for both default, and SHORT youtube url
2

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

3 Comments

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/ ?
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.
+1 Entirely forgot about groupings behavior. I also edited and posted before I realised another had replies, so sorry about that.
1

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.

3 Comments

Please see the updated question, need output like youtube.com/v/136pEZcb1Y0
Just extract the parenthesized group and add it to the string "youtube.com/v"
Isn't that what's in my answer?

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.