$str = 'youtube.com/watch?v=iNAMI8DQc8M';
$id = get_id($str);
function get_id($str) {
$matches = array();
if (preg_match('/youtu\.?be\/?(\.com\/watch\?v=)?([\w]+)/', $str, $matches)) {
$id = $matches[2];
}
return $id;
}
It's extremely tolerant, but it works.
We know youtu will be there no matter what, so there it is. youtu
The first part checks for a . before be. It could be there, but doesn't need to be there. \.?be
There is a check for the .com/watch?v= part, too, which is also unnecessary, but okay to have. (\.com\/watch\?v=)?
After that, we match the video ID. ([\w]+)