How to get youtube video code from a URL

hello guys,
I’m using youtube API to post videos to my website, this API needs only the vid ID which is to be posted.
Can anyone tell me how can i get a video ID from a youtube URL?

for example from these URLs i want only the red part:

urls can contain different parameters but i want only the string between the “v=” till it meets an “&” or end of the string.


	$str = '';
	preg_match('~v=([A-Za-z0-9]+)~', $str, $match);

Hey, thanks for the answer :slight_smile: however isnt there any simpler way that works like i said? anything between “v=” and “&” or end of string?
I say it because that string may contain about anything, not only letters/numbers, an example of link is this:

So if its possible to do it the way i want it’ll be better, if not then i can use the regex u gave while just adding ‘-’ and hope no other special chars will pop-up :slight_smile:

You can use a dot like this to match any character

preg_match('~v=(.*?)&~', $str, $match);

hey thanks, however i tested it and it didn’t work on the last example i gave when there’s no amp (&) in the string at all, any solution?

try this

$str = '';
$pattern = '#v=([^&]+)#i';
if (preg_match($pattern, $str, $match))
        $id = $match[1];
        echo $id;

works in all situations, thank you both for the help.