How to: detect URLs in text and convert to html links (PHP using regular expressions)
October 14th, 2009
I was trying to find a way of picking up URLs from user’s posts and converting them to HTML links. I found a few examples on the net that didn’t work for multiple URLs so I thought i would post a simple solution.
I have used the PHP preg_replace function
1 2 3 4 5 6 7 8 9 10 11 | <?php // The Regular Expression filter $pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; //example text $text="Example user text with a URL http://www.zero7web.com , second link http://www.didsburydesign.co.uk"; // convert URLs into Links $text= preg_replace($pattern, "<a href=\"\\0\"?phpMyAdmin=uMSzDU7o3aUDmXyBqXX6JVQaIO3 rel=\"nofollow\">\\0</a>", $text); echo $text; ?> |
This will match all the URL’s in the text and not just the first one like so many of the example on the web seem to do!!
I will post a C# .net version of this as a follow up in the next day or so.
All comments welcome.
Zero7Web Categories: Development convert, links, php, preg_replace, regular expressions, URL, url detection