preg_match返回“注意:未定义的偏移量”。

3
我正在制作一个Torrent PHP爬虫,但我遇到了问题,以下是我的代码:

// ... 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/>";

这是一个HTML页面(“类型”表示类别,“电影”表示电影):

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

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

标题已经显示了,但分类却没有显示,为什么呢?我尝试使用$categorymatches[0]$categorymatches[2]$categorymatches[3]进行输出,但没有成功。


这意味着contents不会与categorymatches匹配。另外,注释使用-->而不是--!>关闭。 - Explosion Pills
$contents 不包含正确的 HTML 数据。尝试在 curl_exec() 后立即输出它,看看会出现什么。我使用您提供的 HTML 在本地尝试过,并且可以正常工作,完全匹配。 - entropid
1个回答

6
您假设了preg_match实际上已经找到了匹配项。最好的方法是测试它是否这样做了。
$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
}

请注意,在使用 preg_match 时可能需要使用一个或两个开关:只有在使用 "title" 而不是 "TITLE" 或 "Title" 时才能找到结果,因此使用大小写不敏感的 /i 开关可能是个好主意;或者标签可能位于不同的行上,所以换行符开关 /m 可能会有用。对于所有的 preg_match 检查都适用相同的原则。
编辑:看起来您的类别匹配正在测试 utf-8 字符串,因此尝试使用 /u 开关。

是的,问题出在字符集上 - 我只需将crawler.php转换为ANSI格式,现在它可以工作了(被爬取的页面采用Windows-1251编码) :) 谢谢! - user1204111
这不应该是 if ($matchCount > 0) -> 找到匹配吗? - Urs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接