tags:

views:

54

answers:

2

I need to insert a string directly after the open anchor ends (where the anchor content starts).

Here is my code:

<ul id="menu-topmenu2" class="menu">
    <li id="menu-item-5" class="menu-item menu-item-type-post_type menu-item-5">
        <a href="http://localhost/domain/barnlager.se/?page_id=2"&gt;
            About
        </a>
    </li>
    <li id="menu-item-5" class="menu-item menu-item-type-post_type menu-item-5">
        <a href="http://localhost/domain/barnlager.se/?page_id=2"&gt;
            Services
        </a>
    </li>
</ul>

In this example I need content before "About" and "Services". A short regexp should do it? The HTML code above can be a string called $content.

I use PHP. Thanks!

+1  A: 

You can find every anchor tag with /<a.*?>/i. If you want to replace something after that, the call would look like preg_replace("/(<a.*?>)/", '$1YOUR ADDITIONAL TEXT', $content).

If for whatever reason you need a double-quoted string as the replacement argument, make sure to backslash-escape the $1.

Matt Kane
+2  A: 

I'd use parser, DOM for instance:

$content = '...your html string...';
$doc = new DOMDocument();
$doc->loadHTML('<html><body>'.$content.'</body></html>');
$x = new DOMXPath($doc);
foreach($x->query('//a') as $anchor){
    // strrev(trim($anchor->nodeValue))) is just an example. put anything you like.
    $anchor->insertBefore(new DOMText(strrev(trim($anchor->nodeValue)))),$anchor->firstChild);
}
echo $doc->saveXML($doc->getElementsByTagName('ul')->item(0));

And as an added bonus it throws a warning you have defined id="menu-item-5" twice in your HTML, which is not valid.

Wrikken
Almost as I coded it. Yours might be even better? $dom = new DOMDocument(); $dom->loadHTML($content); $xpath = new DomXPath($dom); $tag = $dom->getElementsByTagName("a"); $counter = $tag->length; for ($i = 0; $i < $counter; $i++) { $result = $tag->item($i)->nodeValue; $content = str_replace($result, '<img src="http://www.google.com/s2/favicons?domain=seo.getupdated.se }
Jens Törnell
The `getElementsByTagName` could actually be faster and eliminate the need for `DOMXPath` altogether. I would not try to use a `str_replace` on the original content however: firstly, `DOMDocument` has a knack of translating entities, secondly: it is by no means guaranteed that your `$result` doesn't literally appear somewhere else, resulting in improper replacements. If you already have the stuff in `DOM`, just add an DOMElement with the DOM functions at the proper location.
Wrikken