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

2 php curl web-crawler preg-match

我正在制作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/>";
Run Code Online (Sandbox Code Playgroud)

HTML页面("Тип"表示类别,"Филми"表示电影):

<title>The Matrix</title>
<!--Some Codes Here--!>
<tr><td>???</td><td valign="top" align=left>?????</td></tr>
<!--Some Codes Here--!>
Run Code Online (Sandbox Code Playgroud)

结果:

Title - The Matrix
Notice: Undefined offset: 1 in /var/www/spider.php on line 117
Run Code Online (Sandbox Code Playgroud)

它显示的是标题但不是类别..为什么会这样?我试图呼应$categorymatches[0],$categorymatches[2],$categorymatches[3]没有任何的运气.

Mar*_*ker 5

您假设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
}
Run Code Online (Sandbox Code Playgroud)

请注意,您可能希望使用一个或两个带有preg_match的开关:这只会在使用"title"时找到结果,而不是"TITLE"或"Title",因此使用不区分大小写的/ i开关可能是一个想法; 或者标签可能位于与该值不同的行上,因此多行开关/ m可能很有用.

同样的原则适用于所有preg_match检查

编辑

看起来您的类别匹配正在测试utf-8字符串,因此请尝试使用/ u开关