Skip to content

Instantly share code, notes, and snippets.

@eiszfuchs
Created April 4, 2012 17:10
Show Gist options
  • Save eiszfuchs/2303891 to your computer and use it in GitHub Desktop.
Save eiszfuchs/2303891 to your computer and use it in GitHub Desktop.
<?php
function find_urls_url_callback($matches) {
if(strpos($matches[0], '&lt;') !== false) {
return $matches[0];
}
if(strpos($matches[0], '://') === false) {
return "<a class=\"url\" href=\"http://$matches[0]\">$matches[0]</a>";
}
return "<a class=\"url\" href=\"$matches[0]\">$matches[0]</a>";
}
function find_urls_usernames_callback($matches) {
return "<a class=\"screen_name\" href=\"http://twitter.com/$matches[1]\">$matches[0]</a>";
}
function find_urls_hash_callback($matches) {
return "<a class=\"hash\" href=\"http://search.twitter.com/search?q=".urlencode($matches[1])."\">$matches[0]</a>";
}
function find_urls($text) {
$tld = 'ac|ad|aero|ae|af|ag|ai|al|am|an|ao|aq|arpa|ar|asia|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|biz|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|com|co|coop|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|net|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw';
$regex = "{((https?|ftp)://)?[a-z0-9.\-]+\.(?:$tld)((/[a-z0-9.,/\-_?=#\+]*)?(?![a-z]))}i";
$text = preg_replace_callback($regex, "find_urls_url_callback", $text);
$regex = "{@([a-z0-9\-_]+)}i";
$text = preg_replace_callback($regex, "find_urls_usernames_callback", $text);
$regex = "{(?<=^|\s)#([0-9A-Z_]*[A-Z_]+[a-z0-9_üÀ-ÖØ-öø-ÿ]*)}i";
$text = preg_replace_callback($regex, "find_urls_hash_callback", $text);
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment