Jens Törnell
Jens Törnell

Reputation: 24768

Regexp to insert string in the beginning of anchor tag?

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">
            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">
            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!

Upvotes: 2

Views: 364

Answers (2)

Wrikken
Wrikken

Reputation: 70490

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.

Upvotes: 3

Matt K
Matt K

Reputation: 13852

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.

Upvotes: 1

Related Questions