PHP正则表达式以不同的方式获取html标签结尾

时间:2012-09-19 02:33:50

标签: php regex operators

首先,对不起我的英语,这不好。

我有如下表格。

 <table>
  <tr class="_in" id="1">
    <td>content</td>
    <td>content
         <h1>content h1</h1>
    </td>
  </tr>
  <tr class="_in" id="2">
    <td>content</td>
    <td>content
        <table>
            <tr>
                <td>content</td>
            </tr>
        </table>
    <h2>content h2</h2>
    </td>
  </tr>
  <tr class="_in" id="3">
    <td>content</td>
    <td>
            <table>
              <tr>
                <td>content</td>
              </tr>
            </table>
            <h3>content h3</h3>
    </td>   
  </tr>
  <tr class="_in" id="4">
    <td>content</td>
    <td>content
        <h1>content h3</h1>
    </td>
  </tr>
  <tr class="_in" id="5">
    <td>content</td>
    <td>content
        <h1>content h1</h1>
    </td>
  </tr>
</table>

如你所见,我想使用正则表达式来获取tr具有class =“_ in”,但是在tr中有另一个表,并且在该表中有另一个tr标记。除此之外,tr有很多方式的class =“_ in”结尾。 如您所见,它可以以</h1></td></tr></h2></td></tr></h3></td></tr>

结尾

我的解决方案是使用或运算符,但没有结果,下面是我的代码

$html=file_get_contents("vnair3.txt");
$parten='/<tr\sclass=\"_in\"[^>]*>.*(?:<\/h1>|<\/h2>|<\/h3>)\s+<\/td>\s+<\/tr>/isU';
preg_match_all($parten,$html,$output);
print_r($output);

请帮助我让每个tr标签对输出数组中的每个元素都有class =“_ in”。 我用的是php。 谢谢大家

2 个答案:

答案 0 :(得分:0)

修改你的代码,你在每个tr

中得到class =“_ in”
<?php
$html=file_get_contents('vnair3.txt');
$output=str_replace("<tr","<tr class='_in' ",$html,$count);
//echo $output;
print_r($output);
?>

答案 1 :(得分:0)

首先,将HTML粘贴到DOMDocument中。

$dom = new DOMDocument::loadHTML($html_string);

然后找到所有<TR>元素。

$trs = $dom->getElementsByTagName('tr')

然后迭代它们

foreach($trs as $tr) {
    $classes = $tr->getAttribute('class');
    $classes .= " _tr ";
    $tr->setAttribute('class', $classes);
}

然后导出字符串

$html = $dom->saveHTML()

供参考:http://www.php.net/manual/en/class.domdocument.php