PHP - How to convert the YouTube URL with Regex
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=136pEZc开发者_运维技巧b1Y0
into
$url_embedded = http://www.youtube.com/v/136pEZcb1Y0
using Regular Expressions?
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.
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]
!
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.
精彩评论