tags:

views:

327

answers:

1

Hiya,

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.

+1  A: 

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();
jensgram
Hiya - see above - still shows the same error :S
hfidgen
Hiya, I'm looking to find each complete A tag <a href="xx">description</a> and then put $pseudostart before the <a and $pseudoend after the </a>
hfidgen
In that case you would probably want to add the "pseudo elements" as textNodes using `insertBefore()` and `appendChild()` (on the `ahref`'s parent).
jensgram
can you elaborate on how to do that? The PHP manual documentation is less than clear to me.
hfidgen
OK updated the above completely to reflect the new situation - I really need to get this working, I can't see another way of doing it :)
hfidgen