Php parse html dom and count specific rows

2019-03-02 17:58发布

问题:

I'm using the "Simple php DOM Parser" to parse an html table and count its row.

I solved to count all the rows (tr) in it with this code:

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

And I correctly get the number of all the rows in the table.

Now I want to count only the rows which contains a specific td (with a specific string).
We could assume that I want to count only the rows with this td:

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

How can I modify the first code to match this scope?

I tried to use "preg_match" or "preg_match_all" but I don't have much experience in it, so I miss the correct syntax..I think.

Any help is very appreciated!

回答1:

How about:

<?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;
        }
    }
}


回答2:

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