Hello,
I want to change links in a string, so only non-local websites will be opened in a new window.
I came up with the following:
$string = 'I want to open <a href="http://www.mydomain.com">this</a> in a new window. <a href="http://www.php.net">This</a> opens in the same window, and <a href="http://www.mydomain.com">the last one</a> opens in a new window.';
$string = preg_replace('/\href="(.*)"/', 'href="\\1" target="_blank"', $string);
echo $string;
First of all, this replaces only the last link in the string, and there is no difference between local or remote urls.
Then I had something like this:
function chklocal($matches) {
if (stristr($matches[0], "www.mydomain.com")) {
$retval = $matches[0];
} else {
$retval = $matches[0].' target="_blank"';
}
return $retval;
}
$string = preg_replace_callback('/\href="(.*)"/', 'chklocal', $string);
echo $string;
But this still doesn't work.
Can someone help me out?
Thanks...
Arjan