【问题标题】:preg_match returns Notice: Undefined offsetpreg_match 返回注意:未定义的偏移量
【发布时间】:2012-02-11 18:18:00
【问题描述】:

我正在制作 Torrent PHP Crawler,但我遇到了问题,这是我的代码:

// ... 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 创建匹配项。此外,cmets 以 --&gt; 关闭,而不是 --!&gt;
  • $contents 不包含正确的 HTML 数据。尝试在curl_exec() 之后立即回应它,看看会出现什么。我使用您提供的 HTML 在本地进行了尝试,效果很好,完美匹配。

标签: php curl preg-match web-crawler


【解决方案1】:

您假设 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 编码的):) 谢谢!
  • 不应该是if ($matchCount &gt; 0) -> 找到匹配项吗?
猜你喜欢
  • 1970-01-01
  • 2015-08-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2012-02-08
  • 1970-01-01
相关资源
最近更新 更多