Another trick is to protect all existing links by encoding the code, then replacing the URLs with links and then not encoding the protected links.
$data = 'test http://foo <a href="http://link">LINK</a> test';
$data = preg_replace_callback('/(<a href=".+?<\/a>)/','guard_url',$data);
$data = preg_replace_callback('/(http:\/\/.+?)([ .\\n\\r])/','link_url',$data);
$data = preg_replace_callback('/{{([a-zA-Z0-9+]+?)}}/','unguard_url',$data);
print $data;
function guard_url($arr) { return '{{'.base64_encode($arr[1]).'}}'; }
function unguard_url($arr) { return base64_decode($arr[1]); }
function link_url($arr) { return '<a href="'.$arr[1].'">'.$arr[1].'</a>'.$arr[2]; }
The above code is just a proof of concept and does not cope with all situations. However, you can see that the code is pretty simple.
user176959
source
share