PHP – Auto Convert URLs to Links in a Block of Text

Whether you’re creating your own custom blog, tweaking a CMS or building a plugin this is one block of code that can come in very handy. I’ve used this many times over the years and it has always served me well. I will admit, I am terrible with regular expressions and found this a while back, so I can take no credit for it. Usually I use something like txt2re when I a cutomer regular expression.

$pattern = "@\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\@&=+$,%#-]+)*/?)@";

$text = preg_replace($pattern, '<a href="\0">\0</a>', $text_raw);

Hopefully someone else finds it useful 😀


Tags: , , , ,

  • Del.icio.us
  • StumbleUpon
  • Reddit
  • Twitter
  • RSS

6 Responses to “PHP – Auto Convert URLs to Links in a Block of Text”

  1. Have you ever had this not work and bork all of the links? I’m always afraid this is going to happen with wide-scale regular expressions :S

  2. evrix says:

    i added {0,1} after \. at character 188 in $pattern and now it seems to convert raw_text without extension too, which is useful with mod_rewrite.
    an asterisk would have worked too, but my solutions seems more precise

  3. SeanJA says:

    It seems like this might be better done in javascript rather than php, just in case it “borks all of the links” (also you could have an enable/disable links button)

  4. Chad Hutchins says:

    I am having some issues implementing this in javascript. How would you implement this in javascript? Thanks for the post nonetheless.

  5. evrix says:

    ps to my post:
    I realized a simple ‘?’ in place of {0,1} would do…

  6. Pioneer Websites says:

    Great job – very similar to one I saw elsewhere – but adds the effect of picking up www strings which don’t start with http.

    The only loss is that in that case, the http isn’t added to the start of the href!

Leave a Reply