Get youtube video id from youtube url in smarty template?

1.5k views Asked by At

I need to parse and get youtube video id from youtube url inside smarty tpl file. Right now I'm using plugin file to achieve this using php preg_match function. But I want to use Smarty regular expressions to parse instead of the above method.

As I'm getting video URL through smarty loop, I couldn't parse it in php and assign in smarty. Currently I'm using this code to get the video id from PHP plugin file of smarty.

if ($videoURL) {            
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $videoURL, $match)) {
     $video_id = $match[1];
    }

     if (false !== $video_id) {
       return $video_id;
     }
     return false;
}

I'm not sure of how to convert this preg_match to smarty. Can anyone help me out of this problem?

1

There are 1 answers

0
Kieran On BEST ANSWER

Your best bet is going to be extending Smarty with a plugin, specifically a modifier.

You can follow this discussion here to figure out the best method for getting the ID from a youtube URL; it is in fact quite tricky to account for the different types of URL using solely regex (hence the huge expression you have above.)

An example would look something like:

<?php 

function smarty_modifier_youtubeID($string) { 
    parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
    return $my_array_of_vars['v']; 
}

Then drop the above in the plugins/ directory of smarty with a name like modifier.youtube.php. Then proceed to use it in your for loop (within the template file) like so {$value|youtubeID}

The alternative, that I get the feeling you're after, is to do something like so:

{$value|regex_replace:"/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/":'$1'} 

The above will replace the URL with the video ID (assuming $value consists solely of a youtube URL and no other data, otherwise you'll have to modify the expression.)