MrFidge
MrFidge

Reputation: 2105

PHP - dom appendChild() - adding strings around selected html tags using PHP DOM

I'm trying to run through some html and insert some custom tags around every instance of an "A" tag. I've got so far, but the last step of actually appending my pseudotags to the link tags is eluding me, can anyone offer some guidance?

It all works great up until the last line of code - which is where I'm stuck. How do I place these pseudotags either side of the selected "A" tag?

$dom = new domDocument;
$dom->loadHTML($section);
$dom->preserveWhiteSpace = false;
$ahrefs = $dom->getElementsByTagName('a');
foreach($ahrefs as $ahref) {
    $valueID = $ahref->getAttribute('name');
    $pseudostart = $dom->createTextNode('%%' . $valueID . '%%');
    $pseudoend = $dom->createTextNode('%%/' . $valueID . '%%');
    $ahref->parentNode->insertBefore($pseudostart, $ahref);
    $ahref->parentNode->appendChild($pseudoend);
    $expression[] = $valueID; //^$link_name[0-9a-z_()]{0,3}$
    $dom->saveHTML();
}
//$dom->saveHTML();

I'm hoping to get this to perform the following:

<a href="xxx" name="yyy">text</a> 

turned into

%%yyy%%<a href="xxx" name="yyy">text</a>%%/yyy%%

But currently it doesn't appear to do anything - the page outputs, but there are no replacements or nodes added to the source.

Upvotes: 1

Views: 1150

Answers (1)

jensgram
jensgram

Reputation: 31518

In order to make sure that the ahref node is wrapped...

foreach($ahrefs as $ahref) {
    $valueID = $ahref->getAttribute('name');
    $pseudostart = $dom->createTextNode('%%' . $valueID . '%%');
    $pseudoend = $dom->createTextNode('%%/' . $valueID . '%%');
    $ahref->parentNode->insertBefore($pseudostart, $ahref);
    $ahref->parentNode->insertBefore($ahref->cloneNode(true), $ahref); // Inserting cloned element (in order to insert $pseudoend immediately after)
    $ahref->parentNode->insertBefore($pseudoend, $ahref);
    $ahref->parentNode->removeChild($ahref); // Removing old element
}
print $dom->saveXML();

Upvotes: 1

Related Questions