converting text urls to clickable links
today i came across a challenge that i am surprise i have not faced before but it seemed worthy to make a post about. i have been working on a social networking tool for a company and they wanted all urls to automatically be parsed into clickable links regardless of the syntax (ie http://www.site.com, site.com, www.site.com). the solution was extremely simple: write a regular expression to match any url and use to make a comparison. heres the code:
<?php
$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_!~*'().;?:\@&=+$,%#-]+)*/?)@";
$new_text = preg_replace($pattern, '<a href="\0">\0</a>', $old_text);
?>
thats it, simple and effective. this is similar to how Facebook converts any url into a link in a status update. with the url in tack you could then use that url to capture a screenshop of the website and make it display along with the link.
Leave a comment
Tags
AJAX
arrays
ascii art
big-o-notation
concat
data structures
email validation
event handler
gd library
geolocation
getElementById
goal thermometer
hash table
JavaScript/Ajax
json
md5
multithreading
MySQL
obfuscation
object oriented programming
open source
PHP
recursion
regular expression
select statement
star wars
variables
web apps
XML
xml dom
XMLHttpRequest




