doumengmian1180 2012-02-11 18:18
浏览 120
已采纳

preg_match返回通知:未定义的偏移量

I'm making Torrent PHP Crawler and I have problem, here's my code:

// ... the cURL codes (they're working) ...
// Contents of the Page
$contents = curl_exec($crawler->curl);

// Find the Title
$pattern = "/<title>(.*?)<\/title>/s";
preg_match($pattern, $contents, $titlematches);
echo "Title - ".$titlematches[1]."<br/>";

// Find the Category
$pattern = "/Тип<\/td><td(?>[^>]+)>((?>[^<]+))<\/td>/s";
preg_match($pattern, $contents, $categorymatches);
echo "Category - ".$categorymatches[1]."<br/>";

The HTML page ("Тип" means Category and "Филми" means Movies):

<title>The Matrix</title>
<!--Some Codes Here--!>
<tr><td>Тип</td><td valign="top" align=left>Филми</td></tr>
<!--Some Codes Here--!>

The Result:

Title - The Matrix
Notice: Undefined offset: 1 in /var/www/spider.php on line 117

It's showing the title but not the category.. why is that? I've tried to echo $categorymatches[0], $categorymatches[2], $categorymatches[3] without any luck.

  • 写回答

1条回答 默认 最新

  • duanmao1975 2012-02-11 18:27
    关注

    You're assuming that preg_match actually finds a match. It's better to test if it did so.

    $pattern = "/<title>(.*?)<\/title>/s"; 
    $matchCount = preg_match($pattern, $contents, $titlematches); 
    if ($matchCount > 0) {
        echo $titlematches[1]."<br/>";
    } else {
        // do something else, 'cos no match found
    }
    

    Note that you might want to use a switch or two with preg_match: this will only find a result if "title" is used, not "TITLE" or "Title", so using the case-insensitive /i switch might be an idea; or the tag might be on a different line to the value, and to the , so the multiline switch /m could be useful.

    And the same principle applies to all your preg_match checks

    EDIT

    It looks as though your category match is testing for a utf-8 string, so try using the /u switch

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!