从PHP中匹配数据的最有效方法是什么?<table> </table>

时间:2009-09-15 07:46:20

标签: php pattern-matching

例如,从html中删除键/值对,如下所示:

<tr> 
          <td id="td3"  class="td3"  bgcolor="#FFFFFF" colspan="4">■ Related Information </td>

        </tr>
        <tr> 
          <td id="td5" class="td5" width="10%">job title:</td>
          <td id="td5" class="td5" width="90%" colspan="3">Sales Representitive</td>
        </tr>
        <tr> 
          <td id="td5" class="td5" width="10%">Date:</td>

          <td id="td5" class="td5" width="40%">2009-9-15</td>
        </tr>
        <tr> 
          <td id="td5" class="td5" width="10%">Location:</td>

          <td id="td5" class="td5" width="40%">Jiangyin</td>
        </tr>
        <tr> 
          <td id="td5" class="td5" width="10%">Degree:</td>
          <td id="td5" class="td5" width="40%">Bachelor</td>

          <td id="td5" class="td5" width="10%">Major:</td>
          <td id="td5" class="td5" width="40%">No limit</td>
        </tr>
        <tr> 
          <td id="td5" class="td5" width="10%">Sex:</td>
          <td id="td5" class="td5" width="40%">No limit</
        </tr>
        <tr> 
          <td id="td5" class="td5" width="10%">Type:</td>
          <td id="td5" class="td5" width="40%">Fulltime</td>
          <td id="td5" class="td5" width="10%"></td>
          <td id="td5" class="td5" width="40%"></td>
        </tr>

我已经厌倦了写长篇正则表达式。 有更简单的方法吗?

3 个答案:

答案 0 :(得分:5)

使用HTML或XML解析器,例如DOMDocumentSimpleXML。然后,您可以简单地遍历DOM并获取所需的数据。

答案 1 :(得分:2)

您可以使用一些简单的正则表达式:

$values = array();
if (preg_match_all("/<tr>(.*?)<\/tr>/is", $html, $matches)) {
 foreach($matches[1] as $match) {
  if (preg_match_all("/<td[^>]*>([^<]+)<\/td>/is", $match, $tds))
   array_push($values, $tds[1]);
 }
}

var_dump($values);

分离模式而不是单个大模式时要简单得多。

答案 2 :(得分:1)

你应该尝试鲜为人知的PHP Simple HTML DOM Parser。它可以让你做这样的事情:

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
       echo $element->src . '<br>';

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '<br>'; 

// Create DOM from string
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');

$html->find('div', 1)->class = 'bar';

$html->find('div[id=hello]', 0)->innertext = 'foo';

echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>
相关问题