Php parse html dom and count specific rows

一个人想着一个人 提交于 2019-12-02 06:48:29

问题


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


来源:https://stackoverflow.com/questions/10439354/php-parse-html-dom-and-count-specific-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!