2009-07-19 94 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