在下面的函数中,我应该如何初始化$ matches以避免在注释行上抛出未定义的索引?
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;
}
答案 0 :(得分:2)
if ( isset($matches[0][$i]) && !preg_match( '~nofollow~is',$matches[0][$i])...
您可以检查是否设置了此偏移....
编辑:或:
for ( $i = 0; $i <= sizeof($matches[0])-1; $i++){
因为,假设您的$ matches [0]数组有10个选项,它会从 0 变为 9 而不是<你遵循的强> 10 (这是你阵列的大小)?
答案 1 :(得分:1)
if(isset($matches['0'][$i]))
{
$myVariable= $matches['0'][$i];
}
如果ISSET检查有一个奇怪的效果,使该索引可读。 在我的情况下,我可以在print_r中看到数组,但未定义的索引错误使我无法使用它。经过2个小时的调试,我发现了这个,现在它可以工作!!!
答案 2 :(得分:0)
在使用之前添加$matches = array();
。
此外,您可能需要检查以确保数组正在按照您的预期填充。获取未定义的偏移意味着有问题的数组没有所请求的密钥,因此要么它没有使用你期望它使用的密钥,要么它没有填充数组(你也可能想要添加一个检查到在尝试访问它之前,请确保数组中有实际内容。)