Problem in preg_replace


I have a string (this string comes from the database i.e a dynamic string ) that contains 5 <a> tags .For eg:

$str= ‘<a href=“” key1=“value1”>Any string</a><a href=“” key1=“value1” key2=“value2”>Any string</a>
<a key1=“value1” key2=“value2” href=“” key3=“value3”>Any String</a><a key1=“value1” key2=“value2” href=“”>Any string</a>
<a key1=“value1” href=“”>Any string</a>’;

How can i add a separate onclick attribute to the <a> tag in that string ,i.e first <a> tag onclick=“test1()” ,the next <a> tag onclick=“test2()” etc …(By using php preg_replace or another method)
How can i do this If any one knows please help me thanks in advance…

Take a look at the [FPHP]DOMDocument[/FPHP] class, it might be easier to do it that way.

If not, [FPHP]explode[/FPHP] on "<a " and stick it into each split, then [FPHP]implode[/FPHP] it again.

It’s fairly easy with DomDocument:

$str= '<a href="" key1="value1">Any string</a><a href="" key1="value1" key2="value2">Any string</a>
<a key1="value1" key2="value2" href="" key3="value3">Any String</a><a key1="value1" key2="value2" href="">Any string</a>
<a key1="value1" href="">Any string</a>';

$doc = new DOMDocument(); 

$newStr = '';
foreach($doc->getElementsByTagName('a') as $key => $link) {
    $onclick = 'test'.($key+1).'();';
    $link->setAttribute('onclick', $onclick);
    $newStr .= $doc->saveXML($link);

echo htmlentities($newStr);