2015-02-10 41 views
2

这里可能有一个正则表达式错误,但我无法解决它。preg_match_all undefined偏移错误

我得到“Undefined offset: 0”错误,无法获得标题的值。

这是我的代码。 INEEDTHISONE是我想要取得的头衔。

for ($j = 1; $j <= 1; $j++) { 
    for ($i = 0; $i < 5; $i++) { 
     $site = file_get_contents("http://example.com/index.php?route=product/category&path=395&page=$j");  
     preg_match_all('@<div class="name csstwo" title="INEEDTHISONE"><a itemprop="name" href="http://example.com/id/(.*?)/(.*?).html&amp;path=(.*?)">(.*?)</a></div>@', $site, $title);   
     $title[2][$i] = strip_tags($title[2][$i]); // strip tags 
     $title[2][$i] = preg_replace('~.*?>~', '', $title[2][$i]); // remove a tag and messy stuff 

     echo $title[2][$i]."<br>"; // gives undefined offset error. 

} 

详细错误。

line24 = $title[2][$i] = strip_tags($title[2][$i]);

line27 = echo $title[2][$i]."<br>";

Notice: Undefined offset: 0 in /Applications/MAMP/htdocs/test3.php on line 24 

Notice: Undefined offset: 1 in /Applications/MAMP/htdocs/test3.php on line 27 


Notice: Undefined offset: 1 in /Applications/MAMP/htdocs/test3.php on line 24 


Notice: Undefined offset: 2 in /Applications/MAMP/htdocs/test3.php on line 24 

Notice: Undefined offset: 1 in /Applications/MAMP/htdocs/test3.php on line 27 


Notice: Undefined offset: 3 in /Applications/MAMP/htdocs/test3.php on line 24 

Notice: Undefined offset: 1 in /Applications/MAMP/htdocs/test3.php on line 27 


Notice: Undefined offset: 4 in /Applications/MAMP/htdocs/test3.php on line 24 

Notice: Undefined offset: 1 in /Applications/MAMP/htdocs/test3.php on line 27 

回答

0

我改变

preg_match_all('@<div class="name csstwo" title="INEEDTHISONE"><a itemprop="name" href="http://example.com/id/(.*?)/(.*?).html&amp;path=(.*?)">(.*?)</a></div>@', $site, $title);   

preg_match_all('@<div class="name csstwo" title="INEEDTHISONE"><a itemprop="name" href="http://example.com/id/(.*?)/(.*?).html&path=(.*?)">(.*?)</a></div>@', $site, $title); 

和问题就解决了。

&amp; 

引起了问题。

0

尝试改变如下:

for ($j = 1; $j <= 1; $j++) { 
    for ($i = 0; $i < 5; $i++) { 
     $site = file_get_contents("http://example.com.com/index.php?route=product/category&path=395&page=$j");  
     preg_match_all('@<div class="name csstwo" title="INEEDTHISONE"><a itemprop="name" href="http://example.com/id/(.*?)/(.*?).html&amp;path=(.*?)">(.*?)</a></div>@', $site, $title); 
     if(isset($title[2][$i])){ 
      $title[2][$i] = strip_tags($title[2][$i]); // strip tags 
      $title[2][$i] = preg_replace('~.*?>~', '', $title[2][$i]); // remove a tag and messy stuff 

      echo $title[2][$i]."<br>"; // gives undefined offset error. 
     } 
} 
+0

返回空白页面,isset()返回false。 – salep 2015-02-10 09:29:18

+0

是的,这只是没有错误的。你可能会面对其他问题,比如匹配。为此给出您的输入样本和输出样本。这将从'file_get_contents()' – 2015-02-10 09:32:37

+0

得到我通过改变preg_match_all解决了这个问题,但是谢谢你的回答。 – salep 2015-02-10 10:03:39