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->getElementsByTagName('a');
for ( $i = $as->length; --$i >= 0; ) {
$a = $as->item($i);
$aParts = parse_url ( strtolower ( $a->getAttribute('href') ) );
if ( $aParts['host'] !== $localDomain ) {
$a->setAttribute ( 'title', @$a->getAttribute ('title') . " [external link to {$aParts['host']}]" );
$a->setAttribute ( 'target', '_blank' );
} // if
} // for
NodeList::length
- did you have a particular reason for doing it that way? \$\endgroup\$DOMNodeList
implements theTraversable
interface - which means it will behave just like an array when used withforeach
\$\endgroup\$