preg_match_all未定义的偏移量错误

时间:2015-02-10 09:20:07

标签: php regex file-get-contents preg-match-all

这里可能存在正则表达式错误,但我无法解决。

我得到" 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]);

第27行= 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

2 个答案:

答案 0 :(得分: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.
        }
}

答案 1 :(得分: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; 

造成了这个问题。