【问题标题】:php regex to extract data from HTML tablephp 正则表达式从 HTML 表中提取数据
【发布时间】:2009-07-19 20:14:25
【问题描述】:

我正在尝试制作一个正则表达式来从表中取出一些数据。

我现在得到的代码是:

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

但现在我被困住了。

【问题讨论】:

标签: php html regex html-parsing


【解决方案1】:

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

$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);

关于正则表达式的几句话:

  • &lt;tr&gt;
  • 然后是任意数量的空格
  • 然后&lt;td&gt;
  • 然后你想捕捉什么
  • 然后&lt;/td&gt;
  • 还是一样
  • 最后,&lt;/tr&gt;

我使用:

  • 正则表达式中的? 在非贪婪模式下匹配
  • 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 通常不是一个好主意;如果你可以使用真正的解析器,它应该更安全......

【讨论】:

    【解决方案2】:

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

    the loadHTML method

    【讨论】:

      【解决方案3】:

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

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

      找到两段文字。 \1:\2 将成为替代品。

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

      【讨论】:

        【解决方案4】:

        &lt;td&gt;中提取每个内容

            preg_match_all("%\<td((?s).*?)</td>%", $respose, $mathes);
            var_dump($mathes);
        

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            猜你喜欢
            • 2015-08-10
            • 2023-03-27
            • 2010-11-27
            • 2011-06-26
            • 1970-01-01
            • 2015-02-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多