php正则表达式从HTML表中提取数据

时间:2009-07-19 20:14:26

标签: php html regex html-parsing

我正在尝试制作一个正则表达式,用于从表中获取一些数据。

我现在的代码是:

<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>%

但现在我被卡住了。

5 个答案:

答案 0 :(得分:4)

如果你真的想使用正则表达式(如果你真的确定你的字符串总是这样格式的话可能没问题),那么在你的情况下会是这样的:

$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>
  • 然后任意数量的空格
  • 然后<td>
  • 然后你要捕捉什么
  • 然后</td>
  • 再次相同
  • 最后,</tr>

我用:

    正则表达式中的
  • ?以非贪婪模式匹配
  • 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,count必须至少为1,...)

作为旁注:使用正则表达式来解析HTML通常不是一个好主意;如果你可以使用真正的解析器,它应该更安全......

答案 1 :(得分:3)

Tim的正则表达式可能有效,但您可能需要考虑使用PHP的DOM功能而不是正则表达式,因为它在处理标记中的微小更改时可能更可靠。

请参阅the loadHTML method

答案 2 :(得分:1)

像往常一样,应该使用解析器从HTML和其他非常规语言中提取文本 - 正则表达式可能会导致问题。但是,如果您确定数据的结构,可以使用

%<td>((?s).*?)</td>\s*<td>((?s).*?)</td>%
找到两段文字。 \ 1:\ 2然后将被替换。

如果文本不能超过一行,那么删除(?s)位会更安全......

答案 3 :(得分:0)

不要使用正则表达式,请使用HTML解析器。例如PHP Simple HTML DOM Parser

答案 4 :(得分:0)

<td>

中提取每个内容
    preg_match_all("%\<td((?s).*?)</td>%", $respose, $mathes);
    var_dump($mathes);