Parsing Youtube in preg_replace in PHP?

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


10 points

Hi,

I am attempting to parse the video ID of a youtube URL using preg_match. I found a regular expression on this site that appears to work;

(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+

My PHP code is as follows:

<?php
<?
 
$subject "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1";

 
preg_match("(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+"$subject$matches);

 print 
"<pre>";
 
print_r($matches);
 print 
"</pre>";

?>



7 points

Try the following code:

<?php

$url 
"http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1"
 
$pattern getPatternFromUrl($url); //this will retun video id

function getPatternFromUrl($url)
{
$url $url.'&';
$pattern '/v=(.+?)&+/';
preg_match($pattern$url$matches);
//echo $matches[1]; die;
return ($matches[1]);
}

?>

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.