Hello!
I've been trying to replace inbound links with outbound links.
For example, I would like to replace
<a href="www.google.com">www.google.com</a>
with
<a href="www.google.com" onclick="target='_blank'">www.google.com</a>
whilst ignoring any mailto: links.
I have tried the following:
$s = '<a href="http://www.google.com">www.google.com</a> <a href="http://www.google.com">www.google.com</a>';
$pattern = '(<a href="http://[^"]+".*)>([^<]+</a>.*)';
$replacement = '\\1 onclick="target=\'_blank\'">\\2';
$text = ereg_replace($pattern, $replacement, $s);
Now with just one link in the text this works, however it fails with two and only amends the last link in the string.
So I figured I needed a function:
function outboundLinks($text) {
$pattern = '(<a href="http://[^"]+".*)">([^<]+</a>.*)';
$replacement = '\\1 onclick="target=\'_blank\'">\\2';
while (ereg('<a href="[^"]+">[^<]+</a>', $text) != FALSE) {
$text = ereg_replace($pattern, $replacement, $text);
}
return $text;
}
However this function just loops through and adds the onclick="target='_blank'" repeatedly to the last link, over and over again until the browser crashes or the server goes up in smoke :evilgrin:
Now I have very limited knowledge of regular expressions so i'm guessing thats where i'm falling down but any advice would be very much appreciated.
Thanks