Problem in preg_replace

Hi,

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=“http://www.google.com” key1=“value1”>Any string</a><a href=“http://www.google.com” key1=“value1” key2=“value2”>Any string</a>
<a key1=“value1” key2=“value2” href=“http://www.google.com” key3=“value3”>Any String</a><a key1=“value1” key2=“value2” href=“http://www.google.com”>Any string</a>
<a key1=“value1” href=“http://www.google.com”>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="http://www.google.com" key1="value1">Any string</a><a href="http://www.google.com" key1="value1" key2="value2">Any string</a>
<a key1="value1" key2="value2" href="http://www.google.com" key3="value3">Any String</a><a key1="value1" key2="value2" href="http://www.google.com">Any string</a>
<a key1="value1" href="http://www.google.com">Any string</a>';

$doc = new DOMDocument(); 
$doc->loadHTML($str);

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

echo htmlentities($newStr);