透過正則移除 <table>、<tr>、<td> 標籤,以自定義分隔符 {tr}、{td} 替換結尾標籤,再分割重組為「行 → 列」二維陣列。
function get_td_array(string $table): array {
$table = preg_replace('~<table[^>]*>~si', '', $table);
$table = preg_replace('~<tr[^>]*>~si', '', $table);
$table = preg_replace('~<td[^>]*>~si', '', $table);
$table = str_replace('</tr>', '{tr}', $table);
$table = str_replace('</td>', '{td}', $table);
$table = preg_replace('~<[/!]*?[^<>]*>~si', '', $table); // 清除殘留標籤
$table = preg_replace('~(\r\n|\n|\r)[\s]+~', '', $table); // 清除空白行
$table = str_replace([' ', ' '], '', $table); // 清除空格
$rows = explode('{tr}', $table);
array_pop($rows); // 最後一個空元素
$result = [];
foreach ($rows as $row) {
$cols = explode('{td}', $row);
array_pop($cols);
$result[] = $cols;
}
return $result;
}
$html = '<table><tr><td>A1</td><td>B1</td></tr><tr><td>A2</td><td>B2</td></tr></table>';
$data = get_td_array($html);
/*
Array
(
[0] => Array ( [0] => A1, [1] => B1 )
[1] => Array ( [0] => A2, [1] => B2 )
)
*/
rowspan/colspan)無法正確處理。DOMDocument + DOMXPath 遍歷 //table//tr 並逐格 td/text() 解析,語義正確且健壯。