-1

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;
}
  • Does this answer your question? [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Nico Haase Mar 21 '23 at 11:57

1 Answers1

2

If the provided input doesn't match the regular expressions, you can just add an else and handle the invalid input there. For example, if you want to return null:

if (preg_match($longUrlRegex, $this->video_link, $matches)) {
    $youtube_id = $matches[count($matches) - 1];
} else if (preg_match($shortUrlRegex, $this->video_link, $matches)) {
    $youtube_id = $matches[count($matches) - 1];
} else {
    return null;
}

Note that the two existing if blocks are now chained with an else if so they're mutually exclusive, so now all three potential conditions are covered.

David
  • 208,112
  • 36
  • 198
  • 279
  • I tried to do this, but if I have one link normal, and the other is not, then no output at all. And null should be returned only for the one with the wrong link – broken heart Mar 21 '23 at 11:58
  • let's say I have a foreach where there are several such $item->getYoutubeEmbedUrl() elements, and if there is at least one crooked link, then null will apply to all – broken heart Mar 21 '23 at 11:59
  • @brokenheart: Please clarify the problem. What exactly do you mean by "all" in this case? The only input given in the code shown is the single value `$this->video_link`. In this suggested change, all the code does is check that input against two different regular expressions (which your original code already did) and add a default case to `return null` if neither expression matches (which is what you were attempting to do). What exactly isn't working? – David Mar 21 '23 at 12:02
  • everything, figured it out, it works, thanks for the answer – broken heart Mar 21 '23 at 12:04