我在制作 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]
但没有任何运气。
最佳答案
您假设 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 开关
关于php - preg_match 返回通知 : Undefined offset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9242741/