1

好的,所以 preg_match_all 对雅虎不起作用。

我正在尝试 preg_match_all 使用 cURL curl_multi_getcontent 方法从 Yahoo 获得的结果。

我已成功获取该站点等,但是当我尝试获取链接的结果时,它不会匹配任何内容。当我在 Notepad++ 中使用正则表达式时,它成功但显然不是在 PHP 中。

我目前正在使用:

preg_match_all(
    '#<span class="url" id="(.*?)">(.+?)</span>#si', $urlContents[2], $yahoo
);

例如,检查 HTML,[http://se.search.yahoo.com/search?p=random&toggle=1&cop=mss&ei=UTF-8&fr=yfp-t][1]您会看到所有链接都以 . 开头<span class="url" id="something random">和结尾</span>

有人可以帮助我如何检索这些信息吗?我只需要每个结果的实际链接地址。

整个 PHP 脚本

public function multiSearch($question)
{
    $sites['google'] = "http://www.google.com/search?q={$question}&gl=sv";
    $sites['bing'] = "http://www.bing.com/search?q={$question}";
    $sites['yahoo'] = "http://se.search.yahoo.com/search?p={$question}";

    $urlHandler = array();

    foreach($sites as $site)
    {
        $handler = curl_init();
        curl_setopt($handler, CURLOPT_URL, $site);
        curl_setopt($handler, CURLOPT_HEADER, 0);
        curl_setopt($handler, CURLOPT_RETURNTRANSFER, 1);

        array_push($urlHandler, $handler);
    }

    $multiHandler = curl_multi_init();
    foreach($urlHandler as $key => $url)
    {
        curl_multi_add_handle($multiHandler, $url);
    }

    $running = null;
    do
    {
        curl_multi_exec($multiHandler, $running);
    }
    while($running > 0);

    $urlContents = array();
    foreach($urlHandler as $key => $url)
    {
        $urlContents[$key] = curl_multi_getcontent($url);
    }

    foreach($urlHandler as $key => $url)
    {
        curl_multi_remove_handle($multiHandler, $url);
    }

    foreach($urlContents as $urlContent)
    {
        preg_match_all('/<li class="g">(.*?)<\/li>/si', $urlContent, $matches);
        //$this->view_data['results'][] = "Random";
    }
    preg_match_all('#<cite>(.+?)</cite>#si', $urlContents[1], $googleLinks);
    preg_match_all('#<span class="url" id="(.*)">(.+?)</span>#si', $urlContents[2], $yahoo);
    var_dump($yahoo);
    die();
    $findHtml = array('/<cite>/', '/<\/cite>/', '/<b>/', '/<\/b>/', '/ /', '/"/', '/<strong>/', '/<\/strong>/');
    $removeHtml = array('', '', '', '', '', '', '', '');
    foreach($googleLinks as $links => $val)
    {
        foreach($val as $link)
            $this->view_data['results'][] = preg_replace($findHtml, $removeHtml, $link);
        break;
    }
}
4

1 回答 1

2

首先,您不应该使用正则表达式来处理 HTML。有相当不错的 DOM 解析器可用于 PHP。例如:

$d = new DOMDocument;
$d->loadHTML($s);
$x = new DOMXPath($d);
foreach ($x->query('//span[@class="url"]') as $node) {
        // process each node the way you wish
        // print the id for instance
        echo $node->getAttribute('id'), PHP_EOL;
}

除此之外,除了id="(.*)"贪婪之外,表达式应该可以工作;可以通过以下方式修复:

#<span class="url" id="(.*?)">(.+?)</span>#si

id="...">;之后可能有更多文字。这将使表达式变为:

#<span class="url" id="(.*?)"[^>]*>(.+?)</span>#si
于 2012-10-17T08:33:47.833 回答