You can try using an HTML parser like DOMDocument.
Here's an example:
$html =
'<!DOCTYPE HTML>
<html>
<head></head>
<body>
<h1 style="color: #333;">1</h1>
<div style="width: 180px;">2</div>
</body>
</html>';
$doc = new DOMDocument();
$doc->loadHTML($html);
$doc->encoding = 'UTF-8'; //Appropriate encoding HERE
$root = $doc->documentElement;
var_dump($doc->saveHTML());
iterate($root);
var_dump($doc->saveHTML());
function iterate($node)
{
if($node->nodeType === XML_TEXT_NODE) {
$node->nodeValue = en2ar($node->nodeValue);
}
if ($node->hasChildNodes()) {
$children = $node->childNodes;
foreach($children as $child) {
iterate($child);
}
}
}
To save the output to a variable use:
$var = $doc->saveHTML();
Output:
string '<!DOCTYPE HTML>
<html><head></head><body>
<h1 style="color: #333;">1</h1>
<div style="width: 180px;">2</div>
</body></html>
' (length=135)
string '<!DOCTYPE HTML>
<html><head></head><body>
<h1 style="color: #333;">۱</h1>
<div style="width: 180px;">۲</div>
</body></html>
' (length=147)