My HTML table:
$table = <<< EOD
<table>
<tbody>
<tr style="border:none;">
<td>1</td>
<td>[[name_21]]</td>
<td>[[charge_2]]</td>
</tr>
<tr style="border:1px solid #aaa;">
<td>2</td>
<td>[[name_13]]</td>
<td>[[charge_5]]</td>
</tr>
<tr style="border:1px solid #ccc;">
<td>3</td>
<td>[[name_24]]</td>
<td>[[charge_13]]</td>
</tr>
<tr style="border:1px solid #555;">
<td>4</td>
<td>[[name_22]]</td>
<td>[[charge_22]]</td>
</tr>
</tbody>
</table>
EOD;
This is how I get all charge_X values.
preg_match_all('/\[\[charge_(\d+)\]\]/', $table, $charge_ids);
Remove table row that has charge_13 in its cell.
if (isset($charge_ids)) {
if (array_key_exists('1', $charge_ids)) {
$charge_ids = $charge_ids[1];
$table_replaced = $table;
foreach ($charge_ids as $charge_id) {
if ($charge_id == '13') {
// this line is removing table row if condition met in table cell.
$table_replaced = preg_replace('/<tr[^>]*>(\[\[charge_'.$charge_id.'\]\])<\/tr>/iUums', 'a', $table_replaced);
}
}
echo $table_replaced;
}
}
This code still doesn't work. How to remove table row if table cell has charge_13 in it?
- In
td
may contain just charge_X or charge_X with text. for example:<td>[[charge_13]] USD</td>
- The charge_X value may contain in different order of table cell. for example:
<tr><td>3</td><td>[[charge_13]]</td><td>[[name_24]]</td></tr>
- There may be unicode text in table cell, such as Chinese or Thai characters.
- preg_replace or DOMDocument are welcome.