Looping through DOM to modify elements I'm using this PHP to modify A elements in a DOM fragment (a vBulletin $post['message'] if that matters) so that links to external sites always open new tabs. This is actually the default in vBulletin but it's not always reliable. Anyway, the code works, but looking at the loop makes me think it could be done better. Any suggestions?

$as = $doc-&gt;getElementsByTagName('a');
for ( $i = $as-&gt;length; --$i &gt;= 0; ) {
    $a = $as-&gt;item($i);
    $aParts = parse_url ( strtolower ( $a-&gt;getAttribute('href') ) );
    if ( $aParts['host'] !== $localDomain ) {
        $a-&gt;setAttribute ( 'title', @$a-&gt;getAttribute ('title') . " [external link to {$aParts['host']}]" );
        $a-&gt;setAttribute ( 'target', '_blank' );
    }   // if
} // for
To make it elegant clean code I would:


make proper use of blank lines;
abide by the coding standards defined by PHP-FIG;
use the DOMNodeList object as an array so I can use foreach();
be consistent with either single ' or double quotes ";
use a guard clause.


Refactored code:

$aEls = $doc-&gt;getElementsByTagName('a');

foreach ($aEls as $a) {
    $url = parse_url(strtolower($a-&gt;getAttribute('href')));

    if ($url['host'] === $localDomain) {
        continue;
    }

    $title = $a-&gt;getAttribute('title') . ' [external link to ' . $url['host'] . ']';

    $a-&gt;setAttribute('title', $title);
    $a-&gt;setAttribute('target', '_blank');
}


(not tested)