Reputation: 2364
Had a look round but couldn't find a working (and recent) solution for this.
Using an API I am receiving a string like this:
<object width="600" height="338">
<param name="movie" value="http://www.youtube.com/v/ItT88H3nAWw?version=3&feature=oembed"></param>
<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/ItT88H3nAWw?version=3&feature=oembed" type="application/x-shockwave-flash" width="600" height="338" allowscriptaccess="always" allowfullscreen="true"></embed>
</object>
What would be a regular expression in PHP to extract just the video id? e.g. ItT88H3nAWw
Upvotes: 1
Views: 824
Reputation: 23542
Regexp is ugly. Use something like: getBetween('www.youtube.com/v/', '?version')
Ok, here another version. Assuming $s
is your string and youtube does not change it's ID length:
$p = strpos($s, 'youtube.com/v/') + count('youtube.com/v/');
$id = substr($s, $p, count('ItT88H3nAWw') );
Upvotes: 0
Reputation: 152216
Get src
param from embed
tag WITHOUT regexp. Then parse it in following way:
$youtubeUrl = 'http://www.youtube.com/v/ItT88H3nAWw?version=3&feature=oembed';
if ( preg_match('youtube\.\w+.*?v[/=](\w+)', $youtubeUrl, $matches) ) {
$youtubeId = $matches[1];
}
This regexp will handle both:
To convert HTML string to an object use SimpleXMLElement
.
$obj = new SimpleXMLElement($htmlCode);
$youtubeUrl = $obj->embed->src;
Upvotes: 1