Jump to content

preg_match returns Notice: Undefined offset


Go to solution Solved by iamLearning,

Recommended Posts

I understand the problem, but I do not know how to fix this.

 

 

I am using preg_match function here:

function youtube_id_from_url($link) {
    $pattern = 
        '%^# Match any youtube URL
        (?:https?://)?  # Optional scheme. Either http or https
        (?:www\.)?      # Optional www subdomain
        (?:             # Group host alternatives
          youtu\.be/    # Either youtu.be,
        | youtube\.com  # or youtube.com
          (?:           # Group path alternatives
            /embed/     # Either /embed/
          | /v/         # or /v/
          | /watch\?v=  # or /watch\?v=
          )             # End path alternatives.
        )               # End host alternatives.
        ([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
        $%x'
        ;
    $result = preg_match($pattern, $link, $matches);
    if (false !== $result) {
        return $matches[1];
    }else{
    return false;
}
}

Everything works with my code here as long as preg match finds a match. If it does not find a match it gives me this notice. How would I fix this?

<?php
include 'functions/common.php';
include 'dbconnect.php';


$link = $_POST['submit'];

//Start Youtube Video Submit Process
$youtubeid = (youtube_id_from_url($link)); //Get Youtube ID from URL

if (checkYoutubeOnline($youtubeid) == 1){
	
	   echo "The Youtube video seems to work fine The ID is ".$youtubeid
	
	}else{
		echo 'Sorry that Youtube video does not exist! Please check that your link is correct and that the video is still online.';
	}



?>

<form action="submit_video.php" method="post">
   <p>Link to video: <input type="text" name="link" /></p>
   <input type="submit" name="submit" value="Submit" />
</form>

  • Solution
false !== $result
preg_match() returns a number corresponding to how many matches were found (ie, 0 or 1). It never returns false.

 

Embrace the loose typing.

if ($result) {

You are a life saver! Thank you so much! LOL i did not realize that.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.