-1

Possible Duplicate:
php regex - find all youtube video ids in string

I'm looking for a function that will allow me to change all Youtube links to Javascript function call with ID.

I will show you my code, but it's wrong... not working as i want...:

function find_and_replace_youtube_links(message)
{
    return message.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, 'play_youtube(\'$1\')');   
}

function play_youtube(youtube_id)
{
    $('#youtube_embed').html('something youtubeid something');   
}

The calling

    alert(find_and_replace_youtube_links('test \n\
            http://www.youtube.com/watch?v=JGCsyshUU&feature=autoplay&list=sSPDBAE171ADC2D71FA&playnext=1\n\
\n\
testt http://www.youtube.com/watch?v=JGCsyshUU&feature=autoplay&list=sSPDBAE171ADC2D71FA&playnext=1 testt\n\
\n\
testtt'));

And output

test 
            play_youtube('JGCsyshUU&feature=autoplay&list=sSPDBAE171ADC2D71FA&playnext=1')

testt play_youtube('JGCsyshUU&feature=autoplay&list=sSPDBAE171ADC2D71FA&playnext=1 testt')

testtt

Hmmm...

The problem is here:

 play_youtube('JGCsyshUU&feature=autoplay&list=sSPDBAE171ADC2D71FA&playnext=1')

You can see, that it parse all link, not just id It should give me

play_youtube('JGCsyshUU');

instead of

play_youtube('JGCsyshUU&feature=autoplay&list=sSPDBAE171ADC2D71FA&playnext=1')

with is wrong

:-(

Anyone doing something similar and have working function? I can adapt to my requirements but need to have something in common with mine requirements.

http://www.youtube.com/watch?v=JGCsyshUU-A

Community
  • 1
  • 1
marc234
  • 13
  • 3

1 Answers1

0

Your regular expression is grabbing the rest of the URI's query string from the v parameter onwards.

What you want is to grab only the v parameter and ignore all following parameters.

Parameters are separated by the & character, so instead of matching all characters with (.+), try matching all "non & characters" with ([^&]+).

Here's the modified version of the function in full:

function find_and_replace_youtube_links(message)
{
    return message.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([^&]+).*/g, 'play_youtube(\'$1\')');   
}

Now this is still going to fail if you run it on text where there are any links with just the v parameter and no others since there will then be no & character either. I'll leave the full solution for that case to you as an exercise (-:

hippietrail
  • 15,848
  • 18
  • 99
  • 158