PHP Auto-link Function

function auto_link($text) {
  $pattern = '/(((http[s]?:\/\/(.+(:.+)?@)?)|(www\.))[a-z0-9](([-a-z0-9]+\.)*\.[a-z]{2,})?\/?[a-z0-9.,_\/~#&=:;%+!?-]+)/is';
  $text = preg_replace($pattern, ' <a href="$1">$1</a>', $text);
  // fix URLs without protocols
  $text = preg_replace('/href="www/', 'href="http://www', $text);
  return $text;
}

Note: Code updated on February 7, 2014 to allow single letter domains and exclamation points in URLs and a few additional tweaks for better matching.

25 thoughts on “PHP Auto-link Function”

  1. the fix didn’t work
    needs to be
    $text = preg_replace($pattern, “<a href=”$1″ rel=”nofollow”>$1</a>”, $text);

    But other than that, thank you very much.

  2. Frank: Aside from add the “rel” attribute, how is your code different? I use this auto_link() function all the time and I’ve never had a problem with it.

  3. Something else!
    Email in the string is interpreted (eg. test@sample.com) as a url

    Sorry. Should of use tags for the code

    $text = preg_replace($pattern, "<a href="$1" rel="nofollow">$1</a>", $text);

  4. Not sure how to show the code

    $text = preg_replace($pattern, “<a>$1</a>”, $text);

    \ ” $1 \ “

  5. My site has frames, and when I use your function on links it’s open in the same frame, but I need to open it in a new window, how to fix it?

  6. @Stastonix: All you need to do is add the target attribute to line #3.

    $text = preg_replace($pattern, ” <a href=’$1′ target=”_blank” rel=”nofollow”>$1</a>”, $text);

  7. @Clément: I just tested the function on “http://site.com” and it worked just fine. If you still have problems, let me know.

  8. Thank you for this function, very useful.
    Nevertheless, it doesn’t work when there’s a comma (,) in URL.
    Could you improve your function ?
    Thank you in advance

  9. Dear Andy, more and more url include colon (:). Could you improve your function ?
    Thank you in advance :-)

  10. @Christophe Can you provide a sample URL? I have updated the function to match colons in general, but I’d like to ensure it properly matches the URLs you are trying to auto-link.

  11. @Christophe The update I made today should match that URL fine. Let me know if you have any problems.

  12. Excellent function. Works almost perfect for me. I modified it to open the link in a new window which is normally my default:

    function auto_link($text) {
    $pattern = ‘/(((http[s]?:\/\/(.+(:.+)?@)?)|(www\.))[a-z0-9](([-a-z0-9]+\.)*\.[a-z]{2,})?\/?[a-z0-9.,_\/~#&=:;%+!?-]+)/is’;
    $text = preg_replace($pattern, ‘ $1‘, $text);
    // fix URLs without protocols
    $text = preg_replace(‘/href=”www/’, ‘href=”http://www’, $text);
    return $text;
    }

    Thanks for posting this function.

Leave a Reply

Your email address will not be published. Required fields are marked *