There is a function that highlights the links in the text. Links like: http://google.com and www.google.ru stand out successfully, but google.ru is not highlighted. That is, you need a third regular expression for replacing links like google.ru

function link_it($text) { // преобразование текста в ссылку $text = preg_replace('/(http:\/\/([\w\d\.\?\&\#\;\:\+\-\=\%\/]+))/i', '<a href="$1">$1</a>', $text); $text = preg_replace('/(www.([a-zA-Z_0-9\.\?\&\#\;\:\+\-\=\%\/]*))/i', '<a href="http://$1">$1</a>', $text); return($text); } 

    1 answer 1

    Try it:

     /(([az]+:\/\/)?(?:[a-zа-я0-9@:_-]+\.)+[a-zа-я0-9]{2,4}(?(2)|\/).*?)([-.,:]?(?:\\s|\$))/is 

    Includes:
    - all imaginable and not conceivable protocols, as well as their absence.
    - any number of subdomains.
    - Cyrillic in the name of the site, which is relevant in our time for the Russian Federation.
    - the link ends in a space or where the end of the line.
    - the link must contain a slash, otherwise, besides google.ru, the expression will catch system.time.getLocalTime ()
    Using:

     $text=<<<HEREDOC http://Google.com/test Google.com Google.com/test http://Google.com HEREDOC; echo preg_replace("/(([az]+:\/\/)?(?:[a-zа-я0-9@:_-]+\.)+[a-zа-я0-9]{2,4}(?(2)|\/).*?)([-.,:]?(?:\\s|\$))/is",'<b>$1</b>$3', $text); 

    Result:

    http://Google.com/test
    Google.com
    Google.com/test
    http://Google.com

    • hmm but after all in real life no one writes a slash at the end of the link, right? so it is necessary to catch, apparently, according to the list of TLDs. - VladD
    • Usually they write :) Most links do not lead to the root of the site, but to some page. If without a slash, then a protocol is necessary then otherwise it will find any words written together through a period. Complicate this expression a little later and update the answer. - ReinRaus
    • @ReinRaus, then I'll wait for a new expression :)) - ModaL
    • Updated. Now you can without a slash, if there is a protocol. - ReinRaus 4:08
    • @ReinRaus, what about www.google.com? As I understand it, google.com doesn't recognize it either? - ModaL