Reputation: 4253
Users can add texts. This texts can have links.
I'd like do add click to it.
The problem is, some links works like:
links that has no http will not work and will become:
http://mywebsite.com/www.example.com
any ideas how to solve it?
function toLink($titulo){
$url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i';
$titulo = preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', $titulo);
return $titulo;
}
Upvotes: 0
Views: 62
Reputation: 34576
Use preg_replace_callback
instead and you can interrogate the match to see if you need to add the protocol.
function toLink($titulo) {
$url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i';
$titulo = preg_replace_callback($url, function($matches) {
$url = $matches[0];
if (!preg_match('/^https?:\/\//', $url)) $url = 'http://'.$matches[0];
'<a href="'.$url.'" target="_blank" title="'.$url.'">'.$url.'</a>';
}, $titulo);
return $titulo;
}
Upvotes: 1