PHP注意事项-未定义的偏移量1
我对PHP还是相当陌生的。我看到了关于这个通知的其他帖子,但似乎没有一个能说明我的情况。我试图列出另一页的标题(h2元素)。虽然我在这方面取得了成功(标题如下),但我也收到了以下通知: '注意:第26行的未定义偏移量:1 in/Users/jessenichols/Sites/HCS/news.php'PHP注意事项-未定义的偏移量1,php,Php,我对PHP还是相当陌生的。我看到了关于这个通知的其他帖子,但似乎没有一个能说明我的情况。我试图列出另一页的标题(h2元素)。虽然我在这方面取得了成功(标题如下),但我也收到了以下通知: '注意:第26行的未定义偏移量:1 in/Users/jessenichols/Sites/HCS/news.php' <?php function getTitle($Url){ $str = file_get_contents($Url);
<?php
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<h2\>(.*)\<\/h2\>/",$str,$title);
return $title[1];
}
}
if ($handle = opendir('news')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo '<p class="article_selector">'.getTitle('news/'."$entry").'</p>';
}
}
closedir($handle);
}
?>
在getTitle
方法中,检查是否设置了$title[1]
,case not return null,然后在while
循环中,将getTitle()
的结果分配给变量,并检查该变量是否为null,如下所示
<?php
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<h2\>(.*)\<\/h2\>/",$str,$title);
// if $title[1] isn't set, return null
return isset($title[1]) ? $title[1] : null;
}
}
if ($handle = opendir('news')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
// first, get the title
$title = getTitle('news/'.$entry);
// and after check if title is not null
if (null != $title) {
echo '<p class="article_selector">'.$title.'</p>';
}
}
}
closedir($handle);
}
?>
获取背景信息。。。第26行是“返回$title[1];”当您在while
循环的一次迭代中返回$title[1]
时,该正则表达式不匹配。因此,您尝试返回一些不存在的内容