Your Ad Here

Posted By

misteroneill on 08/31/09


Tagged

parse html replace String links urls


Versions (?)

Who likes this?

8 people have marked this snippet as a favorite

vali29
NyX
gripnrip
rene-design
umang_nine
ignace
alberfp
alexteg


Replace URLs in String with HTML Links


 / Published in: PHP
 

URL: http://www.misteroneill.com

This is a simple function to parse a string and turn any URLs it finds into links. Adds a rel attribute to the link with a value of "nofollow" by default.

  1. function replace_urls($string, $rel = 'nofollow'){
  2. $host = "([a-z\d][-a-z\d]*[a-z\d]\.)+[a-z][-a-z\d]*[a-z]";
  3. $port = "(:\d{1,})?";
  4. $path = "(\/[^?<>\#\"\s]+)?";
  5. $query = "(\?[^<>\#\"\s]+)?";
  6. return preg_replace("#((ht|f)tps?:\/\/{$host}{$port}{$path}{$query})#i", "<a href=\"$1\" rel=\"{$rel}\">$1</a>", $string);
  7. }

Report this snippet  

You need to login to post a comment.