function wrap_outer_tables($html) {
$regex = '/<table([^>]*)>([\s\S]*?)<\/table>/i';
$matches = array();
preg_match_all($regex, $html, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$inner_tables = '';
preg_match_all($regex, $match[2], $inner_tables, PREG_SET_ORDER);
if (empty($inner_tables)) {
$replacement = '<div class="q">' . $match[0] . '</div>';
$html = str_replace($match[0], $replacement, $html);
} else {
$inner_html = wrap_outer_tables($match[2]);
$replacement = '<table' . $match[1] . '>' . $inner_html . '</table>';
$html = str_replace($match[0], $replacement, $html);
}
}
return $html;
}
$html = '<table class="любой или без класса"><tbody>
<table class="sdf"><tbody>
</tbody></table>
<table><tbody>
</tbody></table>
</tbody></table>';
$html = wrap_outer_tables($html);
echo $html;
<div class="q"><table class="любой или без класса"><tbody>
<table class="sdf"><tbody>
</tbody></table>
<table><tbody>
</tbody></table>
</tbody></table></div>