2009-07-19 189 views
0

我正在試圖從表格中提取一些數據的正則表達式。php正則表達式從HTML表格中提取數據

我現在已經得到了代碼:

<table> 
    <tr> 
    <td>quote1</td> 
    <td>have you trying it off and on again ?</td> 
    </tr> 
    <tr> 
    <td>quote65</td> 
    <td>You wouldn't steal a helmet of a policeman</td> 
    </tr> 
</table> 

此我想通過更換:

quote1:你想它關閉並重新開啓?

quote65:你不會偷警察

,我已經寫的代碼的頭盔是這樣的:

%<td>((?s).*?)</td>% 

但現在我卡住了。

+0

可能重複與正則表達式?](http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-一,雷傑) – 2011-07-09 21:01:07

回答

3

Tim的正則表達式可能有效,但您可能要考慮使用PHP的DOM功能而不是正則表達式,因爲它在處理標記中的微小更改時可能更可靠。

the loadHTML method

1

像往常一樣,從HTML和其他非常規語言中提取文本應該用解析器來完成 - 正則表達式在這裏可能會導致問題。但是如果你確定你的數據的結構,你可以使用

%<td>((?s).*?)</td>\s*<td>((?s).*?)</td>% 

找到兩段文本。 \ 1:\ 2然後將被替換。

如果文字不能跨越多行,你會更安全丟棄(?s)位...

4

如果你真的想使用正則表達式(如果你真的確定你的弦總是被這樣的格式可能是OK),那這樣的事情,你的情況:

$str = <<<A 
<table> 
    <tr> 
    <td>quote1</td> 
    <td>have you trying it off and on again ?</td> 
    </tr> 
    <tr> 
    <td>quote65</td> 
    <td>You wouldn't steal a helmet of a policeman</td> 
    </tr> 
</table> 
A; 

$matches = array(); 
preg_match_all('#<tr>\s+?<td>(.*?)</td>\s+?<td>(.*?)</td>\s+?</tr>#', $str, $matches); 

var_dump($matches); 

對正則表達式的幾句話:

  • <tr>
  • 然後任意n

      :空格
    • 然後<td>
    • 那麼你想要什麼捕捉
    • 然後</td>
    • ,並再次同
    • 最後,</tr>

    ,而且我用赭

  • ? in th Ë正則表達式來在非貪婪模式匹配
  • preg_match_all讓所有的比賽

然後你讓你在$matches[1]$matches[2](不$matches[0]想要的結果;這裏是我用var_dump的輸出(我已經刪除條目0,使其更短)

array 
    0 => 
    ... 
    1 => 
    array 
     0 => string 'quote1' (length=6) 
     1 => string 'quote65' (length=7) 
    2 => 
    array 
     0 => string 'have you trying it off and on again ?' (length=37) 
     1 => string 'You wouldn't steal a helmet of a policeman' (length=42) 

,那麼你只需要操作這個數組,一些字符串拼接等;舉例來說,像這樣的:

$num = count($matches[1]); 
for ($i=0 ; $i<$num ; $i++) { 
    echo $matches[1][$i] . ':' . $matches[2][$i] . '<br />'; 
} 

,你會得到:

quote1:have you trying it off and on again ? 
quote65:You wouldn't steal a helmet of a policeman 

注意:您應該添加一些安全檢查(如preg_match_all必須返回true,計數必須至少爲1,... )

作爲便箋:使用正則表達式來解析HTML一般不是一個好主意;如果你可以使用一個真正的解析器,它應該是更安全的方式...

0

摘自每個內容<td>

preg_match_all("%\<td((?s).*?)</td>%", $respose, $mathes); 
    var_dump($mathes); 
的[你能提供的,爲什麼它是很難一些例子來解析XML和HTML