2011-02-08 61 views
1

我試圖使用兩個preg_match以從html源代碼中獲取兩個特定值。兩個連續的preg_match

<?php 

    $url = "http://www.example.com"; 
    $userAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"; 
    $ch = curl_init(); 
    curl_setopt($ch,CURLOPT_USERAGENT,$userAgent); 
    curl_setopt($ch,CURLOPT_URL,$url); 
    curl_setopt($ch,CURLOPT_AUTOREFERER,true); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); 
    curl_setopt($ch,CURLOPT_TIMEOUT,10000000); 
    $html = curl_exec($ch); 
    preg_match('~<span class="first">(.*)<\/span>~msU',$html,$matching_data); 
    preg_match('~<span class="second">(.*)<\/span>~msU',$html,$matching_data2); 
    print_r($matching_data); 
    print_r($matching_data2); 
?> 

在這方面採取的$html VAR包含以下順序考慮:

<title>foobar title</title> 
<body> 
<div class="second">Not this one</span> 
<div> 
<span class="first">First</span> 
<span class="second">this one<span> 
</div> 
</body> 

如果我跑我php代碼,第一print_r返回正確的價值:<span class="first">First</span>。但第二個print_r,而不是返回<span class="second">this one<span>它返回<div class="second">Not this one</span>

所以我想preg_match函數開始治療的開始,而不是最後preg_match調用。

如何讓第二個(第三,第四等)呼叫preg_match在最後一次呼叫時運行?

謝謝,

問候。

+0

你可以使用preg_match_all。 – igorw 2011-02-08 13:05:58

回答

3

要連續撥打preg_match,繼續搜索結果從哪裏來,請使用PREG_OFFSET_CAPTURE標誌:

http://php.net/manual/en/function.preg-match.php

至於較大的問題,正則表達式通常不適合解析HTML。您應該使用某種DOM解析器爲您完成這項工作,這就是如果您甚至需要在服務器端完成這項工作。這種事情可以在客戶端使用JavaScript非常簡單(自然而然地)完成 - 您只需將相關值傳回給服務器即可。

0

可以使用偏移捕獲,並在的preg_match功能失調參數(php:preg_match

int preg_match (string $pattern, string $subject [, array &$matches[, int $flags [, int $offset]]])

試試這個:

<?php 

... 

preg_match('~<span class="first">(.*)<\/span>~msU',$html,$matching_data,PREG_OFFSET_CAPTURE); 
preg_match('~<span class="second">(.*)<\/span>~msU',$html,$matching_data2,PREG_OFFSET_CAPTURE, $matching_data[0][1]+strlen($matching_data[0][0])); 
print_r($matching_data); 
print_r($matching_data2); 
0

這是您需要使用的HTML代碼嗎?這不是有效的HTML。您可以使用preg_match_all爲@igorw建議:

preg_match_all('~<(span|div) class="(first|second)">(.*)<\/?span>~msU', $html,$matching_data); 
echo '<xmp>'; print_r($matching_data[0]); 

但是,如果HTML是有效的:

<title>foobar title</title> 
<body> 
<span class="second">Not this one</span> 
<div> 
<span class="first">First</span> 
<span class="second">this one</span> 
</div> 
</body> 

preg_match_all('~<span class="(first|second)">(.*)<\/span>~msU', $html, $matching_data); 
echo '<xmp>'; print_r($matching_data[0]);