So I have written a small bit of code to convert tables to divs for our mobile sites.
Here is an excerpt of the code:
function replaceTables($table, $html) {
$tempTable = preg_replace('/<table[^>]*>(.*?)<\/table>/is', '<div style="width: 90%; margin: auto;">$1</div><div style="clear: both;"></div>', $table);
$html = str_replace($table, $tempTable, $html);
preg_match_all('/(?!<table[^>]*>).*?<tr[^>]*>.*?<\/tr>.*?(?<!<\/table>)/is', $tempTable, $rows, PREG_OFFSET_CAPTURE);
for ($i = 0; $i < count($rows[0]); $i++) {
$tempRow = $rows[0][$i][0];
preg_match_all('/(?!<table[^>]*>).*?<td[^>]*>.*?<\/td>.*?(?<!<\/table>)/is', $tempRow, $cols, PREG_OFFSET_CAPTURE);
$numCols = count($cols[0]);
$colWidth = 100/$numCols;
for ($x = 0; $x < $numCols; $x++) {
$tempCol = $cols[0][$x][0];
$cols[0][$x][0] = preg_replace('/<td[^>]*>(.*?)<\/td>/is', '<div style="width: ' . $colWidth . '%; float: left;">$1</div>', $cols[0][$x][0]);
$tempRow = str_replace($tempCol, $cols[0][$x][0], $tempRow);
}
$tempRow = preg_replace('/<tr[^>]*>(.*?)<\/tr>/is', '<div style="clear: both;">$1</div>', $tempRow);
$tempTable = str_replace($rows[0][$i][0], $tempRow, $tempTable);
}
$html = str_replace($table, $tempTable, $html);
return $html;
}
if ($mobile && $page->type_id != 16) {
// replace tables with divs for better mobile support
preg_match_all('/<table[^>]*>.*?<\/table>/is', $this->html, $tables, PREG_OFFSET_CAPTURE);
for ($y = 0; $y < count($tables[0]); $y++) {
preg_match_all('/<table[^>]*>.*?<\/table>/is', $tables[0][$y][0], $nestedTables, PREG_OFFSET_CAPTURE);
if (count($nestedTables[0]) > 0) {
//echo count($nestedTables[0]) . "<br />";
//print_r($nestedTables[0][0][0]);
for ($y = 0; $y < count($nestedTables[0]); $y++) {
$this->html = replaceTables($nestedTables[0][$y][0], $this->html);
}
}
$this->html = replaceTables($tables[0][$y][0], $this->html);
}
//$this->html = preg_replace('/<table[^>]*>(.*?)<\/table>/is', '<div style="width: 90%; margin: auto;">$1<div style="clear: both;"></div></div>', $this->html);
}
return $this->html;
I am having issues with nested tables, the regular expression is finding the first occurrence of the closing table tag instead of the one I would need it to find.
If someone could lead me in the direction of a better regular expression or a different solution to replace tables with divs that would be great. The solution must be by manipulating a string, so that there will not have to be an overhaul of our templated system.
Thanks