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;
}
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 ?
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!!!
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).
精彩评论