1

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!

2 Answers 2

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot, but an error displays me with your code: "syntax error, unexpected '(', expecting T_STRING or T_VARIABLE or '{' or '$' in", referring to the "foreach($row->('td') as $td) {" line..
Ok, I found out the solution for the error (you missed "find") and now it works great! Thanks a lot !!!
Yeah sorry, I missed that one. Something clearly went wrong with the copy paste :). Fixed it also in the code now.
Don't worry and thanks again. Now I'm facing a stronger challenge regarding this. You can find the new question here: stackoverflow.com/questions/10453380/…
Okay, I'll take a look at it. Actually, it is not much of a stronger challenge.
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;
    }
}

2 Comments

Small mistake in this approach, if a TR has multiple TD's with the target string, your count will be wrong ;).
To answer your doubt, the target string could be contained only one time in each matching row (only one TD's target string for matching row)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.