This is my php function. Its replacing things that are already replaced, thus messing the HTML. How do I prevent a second time replacement on the same text was replaced the first time?
function text2link($str){
$str="\r\n$str\r\n";
$pattern= array(
'/(http:\/\/)(.*?)(\n|\<|"|\s)/is',
'/(https:\/\/)(.*?)(\n|\<|"|\s)/is',
'/\[url\=(.*?)\](.*?)\[\/url\]/is'
//'/[^\"|\>](http:\/\/)([a-zA-Z0-9\?\&\%\.\;\:\/\=\+\_\-]*)[^\"|\<]/is',
//'/[^\"|\>](https:\/\/)([a-zA-Z0-9\?\&\%\.\;\:\/\=\+\_\-]*)[^\"|\<]/is',
//'/[^\"|\>](ftp:\/\/)([a-zA-Z0-9\?\&\%\.\;\:\/\=\+\_\-]*)[^\"|\<]/is'
);
$replace=array( ' <a target="_blank" href="http://$2">$2</a> $3', ' <a target="_blank" href="https://$2">$2</a> $3', '<a target="_blank" href="$1">$2</a>',
//' <a target="_blank" href="http://$2">$2</a> ', ' <a target="_blank" href="https://$2">$2</a> ', ' <a target="_blank" href="ftp://$2">ftp: $2</a> '
);
$str = preg_replace( $pattern, $replace, $str);
return $str;
}
echo text2link(' A link to [url=https://www.google.com] secure google [/url] and www.google.com this is http://www.google.com and another [url=http://www.google.com] google [/url] '); exit;
If you run the code above, you'll see the first link as:
<a target="_blank" href=" <a target="_blank" href="https://www.google.com">">www.google.com]</a> secure google </a>
It should be:
<a target="_blank" href="https://www.google.com"> secure google </a>
For some reason the http part is getting replaced again.
The ones already replaced by the [url] patterns are getting replaced again using previous patterns. The commented patterns are where I tried to detect a quote or a greater/less sign and avoid replace. Didn't work...
'/\[url=([^\]]+)\](.+?)(\[\/url\])/', '<a target="_blank" href="/$1">$2</a>'