Scott B
Scott B

Reputation: 40177

Undefined offset: 0 Error in preg_match

In the function below, how should I initialize $matches to avoid throwing undefined index on the commented line?

function save_rseo_nofollow($content) {
$my_folder =  get_option('rseo_nofollow_folder');
    preg_match_all('~<a.*>~isU',$content["post_content"],$matches);
    for ( $i = 0; $i <= sizeof($matches[0]); $i++){
        if ( !preg_match( '~nofollow~is',$matches[0][$i]) //ERROR UNDEFINED OFFSET HERE!
            && (preg_match('~' . $my_folder . '~', $matches[0][$i]) 
               || !preg_match( '~'.get_bloginfo('url').'~',$matches[0][$i]))){
            $result = trim($matches[0][$i],">");
            $result .= ' rel="nofollow">';
            $content["post_content"] = str_replace($matches[0][$i], $result, $content["post_content"]);
        }
    }
    return $content;
}

Upvotes: 0

Views: 3680

Answers (3)

user2897448
user2897448

Reputation:

if(isset($matches['0'][$i]))
{
$myVariable= $matches['0'][$i];
}

IF ISSET checking has a weird effect, making that index readable. In my case I could see the array in print_r but the undefined index error kept me from using it. After 2 hours of debugging I happended to put this and now it works!!!

Upvotes: 1

Shikiryu
Shikiryu

Reputation: 10219

if ( isset($matches[0][$i]) && !preg_match( '~nofollow~is',$matches[0][$i])...

You can check if this offset... is set.


Edit : or :

for ( $i = 0; $i <= sizeof($matches[0])-1; $i++){

because, let's say your $matches[0] array have 10 choices, it'll go from 0 to 9 and not 10 (which is the size of your array) you follow ?

Upvotes: 2

Shauna
Shauna

Reputation: 9596

Add $matches = array(); before you use it.

Also, you might want to check to make sure the array is filling how you expect it to. Getting undefined offset means the array in question doesn't have the requested key, so either it's not using the keys you're expecting it to use, or it's not filling the array (you'll also probably want to add in a check to make sure there's actually stuff in your array before you try accessing it).

Upvotes: 0

Related Questions