tags:

views:

47

answers:

1

I'm trying to basically extract the ?v= (the query part) of the youtube.com url... it's to automatically embed the video when someone types in a youtube.com URI (i.e. someone will type in http://www.youtube.com/?v=xyz, this program should embed it into the page automatically).

Anyway when I run the following code, I get two QUERY(ies) for the first URI:

<?php
//REGEX CONTROLLER:

//embedding youtube:
function youtubeEmbedd($text)
{
    //scan text and find:
        //  http://www.youtube.com/
        //  www.youtube.com/

$youtube_pattern = "(http\:\/\/www\.youtube\.com\/(watch)??\?v\=[a-zA-Z0-9]+(\&[a-z]\=[a-zA-Z0-9])*?)";      //  the pattern

    #"http://www.youtube.com/?v="

    echo "<hr/>";
    $links = preg_match_all($youtube_pattern, $text, $out, PREG_SET_ORDER);     // use preg_replace here

    if ($links)
    {
        for ($i = 0; $i != count($out); $i++) 
        {
            echo "<b><u> URL </b><br/></u> ";

            foreach ($out[$i] as $url)
            {
                // split url[QUERY] here and replaces it with embed code:
                $youtube = parse_url($url);
                echo "QUERY: " . $youtube["query"] . "<br/>";
                #$pos  = strpos($url, "?v=");
            }          
        }
    }    
    else
    {
        echo "no match";
    }
}

youtubeEmbedd("tthe quick gorw fox http://www.youtube.com/watch?v=5qm8PH4xAss&amp;x=4dD&amp;k=58J8 and http://www.youtube.com/?v=Dd3df4e ");

?>

Output is:

URL QUERY: v=5qm8PH4xAss QUERY: << WHY DOES THIS APPEAR???????????? URL QUERY: v=Dd3df4e

I would be greatful for any help.

+2  A: 

Your regular expression stores a result in $out like this:

(
    [0] => Array
        (
            [0] => http://www.youtube.com/watch?v=5qm8PH4xAss
            [1] => watch
        )

    [1] => Array
        (
            [0] => http://www.youtube.com/?v=Dd3df4e
        )

)

Your regular expression has a subgroup for matching the text watch, and so this ends up as a result in the array.

Since you iterate through all results $out[$i] you're trying to run parse_url on the second result of the first match; this leads to an empty output.

To fix your issue, simple change your iteration to something like:

if($links){
    foreach($out as $result){
        $youtube = parse_url($result[0]);
        echo "<b><u> URL </b><br/></u> QUERY: " . $youtube["query"] . "<br/>";
    }
}
Mark E
There are two URI in the string though, would this work with both?
john mossel
@john This will give you both.
Mark E
Yay, thank you,.. I did what you said, and, removed the for loop, then it worked perfectly.
john mossel