0

Users can add texts. This texts can have links.

I'd like do add click to it.

The problem is, some links works like:

http://www.example.com

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;
}
Moses Schwartz
  • 2,857
  • 1
  • 20
  • 32
RGS
  • 4,062
  • 4
  • 31
  • 67
  • Possible duplicate of [Convert plain text URLs into HTML hyperlinks in PHP](https://stackoverflow.com/questions/1960461/convert-plain-text-urls-into-html-hyperlinks-in-php) – madflow Jan 18 '19 at 13:39
  • @madflow did you read my question? I think not. If you have read you would notice that I have a problem with the same function that you marked as duplicated. links with no http on it will not work. – RGS Jan 18 '19 at 13:41
  • When I try `echo toLink('google.com');` I get **google.com** is this what you want? – Moses Schwartz Jan 18 '19 at 13:43
  • @MoisheySchwartz try www.google.com. it will become www.mywebsite.com/www.google.com . I'd like to add http in front of links to avoid this. – RGS Jan 18 '19 at 13:45

1 Answers1

1

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;
}
Mitya
  • 33,629
  • 9
  • 60
  • 107
  • 1
    You're welcome. Note also that most of your subgroups in the pattern are unnecessary since you're only using the entire match, not the sub-groups, in the output. – Mitya Jan 18 '19 at 13:48
  • I'm trying to make it work but no success, should I place your code inside my toLink function? – RGS Jan 18 '19 at 16:38
  • 1
    See edit. I've now included the entire, edited function. – Mitya Jan 19 '19 at 14:35