I have a function that converts youtube links to embed format
But if I specify a link in the wrong format, or instead of a link in plain text, I get an error
$youtube_id is undefined
public function getYoutubeEmbedUrl()
{
$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_-]+)\??/i';
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))([a-zA-Z0-9_-]+)/i';
if (preg_match($longUrlRegex, $this->video_link, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
if (preg_match($shortUrlRegex, $this->video_link, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
return 'https://www.youtube.com/embed/' . $youtube_id ;
}
I am trying to add validation to the function but I am getting the same error
if (!$youtube_id) {
return null;
}