URL - from YouTube insert HTML - with preg_match

A friend just needed help, he wants people to be able to put the YouTube insert code into a database. However it seems that there are some display related things in there he can live without that people might mess with and of course we don’t want that.


The easiest solution is to simply grab the relevant information and later render the rest of the HTML just like he wants it. Therefore we need the URL including the video ID and nothing else.

To complicate things we need to be able to handle several different services, any further variations than the below two are not possible though. We can for instance calmly assume that the name attribute will always be movie.

$string1 = '<param name="movie" value="http://www.youtube.com/v/ase24sd2_34&somevar=someval">';
$string2 = '<param name="movie" value="http://someservice.com/ase24sd2_34">';

$regex = '/<param name="movie" value="(http:\/\/[^&"\'\s]+)/i';

preg_match_all($regex, $string1, $matches, PREG_SET_ORDER);
print_r($matches);
preg_match_all($regex, $string2, $matches, PREG_SET_ORDER);
print_r($matches);

So we want the result in the parenthesis which basically means get http:// and all characters until we encounter either &, “, ‘ or a white space.

Output:

Array
(
    [0] => Array
        (
            [0] => <param name="movie" value="http://www.youtube.com/v/ase24sd2_34
            [1] => http://www.youtube.com/v/ase24sd2_34
        )

)
Array
(
    [0] => Array
        (
            [0] => <param name="movie" value="http://someservice.com/ase24sd2_34
            [1] => http://someservice.com/ase24sd2_34
        )

)


Related Posts

Tags: , , ,