Php解析html dom并计算特定行

时间:2012-05-03 21:08:20

标签: php parsing dom preg-match preg-match-all

我正在使用“简单的php DOM Parser ”来解析html表并计算其行。

我解决了使用以下代码计算其中的所有行(tr):

$rows = $table->find('.trClass');
$count = count($rows);
echo $count;

我正确地得到了表中所有行的数量。

现在我想只计算包含特定 td (带有特定字符串)的行。我们可以假设我只想计算带有这个td的行:

<td class="tdClass" align="center" nowrap="">TARGET STRING</td>

如何修改第一个代码以匹配此范围?

我尝试使用“preg_match”或“preg_match_all”,但我没有太多经验,所以我想念正确的语法......我想。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

怎么样:

<?php
$targetString = 'TARGET STRING';
$rows = $table->find('.trClass');

$count = 0;
foreach($rows as $row) {
    foreach($row->find('td') as $td) {
        if ($td->innertext === $targetString) {
            $count++;
            break;
        }
    }
}

答案 1 :(得分:0)

$target = 'TARGET STRING';

$n_matchingrows = 0;

$rows = $table->find('tr.trClass');
foreach($rows as $row) {
    $cell = $row->find('td.tdClass[align=center][nowrap=""]', 0);
    if ($cell and $cell->innertext===$target) {
       $n_matchingrows += 1;
    }
}