cpcdev
cpcdev

Reputation: 1214

Rewrite Youtube URL

I have some YouTube URLs stored in a database that I need to rewrite.

They are stored in this format:

$http://youtu.be/IkZuQ-aTIs0

I need to have them re-written to look like this:

$http://youtube.com/v/IkZuQ-aTIs0

These values are stored as a variable $VideoType

I'm calling the variable like this:

$<?php if ($video['VideoType']){
$echo "<a rel=\"shadowbox;width=700;height=400;player=swf\" href=\"" . $video['VideoType'] . "\">View Video</a>";
$}?>

How do I rewrite them?

Thank you for the help.

Upvotes: 1

Views: 694

Answers (2)

CppChris
CppChris

Reputation: 1261

You can use a regular expression to do this for you. If you have ONLY youtube URLs stored in your database, then it would be sufficient to take the part after the last slash 'IkZuQaTIs0' and place it in the src attribute after 'http://www.youtube.com/'.

For this simple solution, do something like this:

<?php 
    if ($video['VideoType']) {
        $last_slash_position = strrpos($video['VideoType'], "/");
        $youtube_url_code    = substr($video['VideoType'], $last_slash_position);
        echo "<a rel=\"shadowbox;width=700;height=400;player=swf\" 
                 href=\"http://www.youtube.com/".$youtube_url_code."\">
                 View Video</a>";
    }
?>

I cannot test it at the moment, maybe you can try to experiment with the position of the last slash occurence etc. You can also have a look at the function definitions:

http://www.php.net/manual/en/function.substr.php

http://www.php.net/manual/en/function.strrpos.php

However, be aware of the performance. Build a script which prases your database and converts every URL or stores a short and a long URL in each entry. Because regular expressions in the view are never a good idea.

UPDATE: it would be even better to store ONLY the youtube video identifier / url code in the database for every entry, so in the example's case it would be IkZuQ-aTIs0.

Upvotes: 1

ArjunShankar
ArjunShankar

Reputation: 23680

You want to use the preg_replace function:

Something like:

$oldurl = 'youtu.be/blah';
$pattern = '/youtu.be/';
$replacement = 'youtube.com/v';
$newurl = preg_replace($pattern, $replacement, $string);

Upvotes: 5

Related Questions