PHP parse url, mailto, and also twitter’s usernames and arguments


/ Published in: PHP
Save to your folder(s)

This small function receive a text as input and returns an html text with links if the source text contains urls (http://www… but also ftp://… and every other protocol), emails, twitter’s usernames (with @ at the beginning) and also twitter tags (with # at the beginning).


Copy this code and paste it in your HTML
  1. function parse_twitter($t) {
  2. // link URLs
  3. $t = " ".preg_replace( "/(([[:alnum:]]+:\/\/)|www\.)([^[:space:]]*)".
  4. "([[:alnum:]#?\/&=])/i", "<a href=\"\\1\\3\\4\" target=\"_blank\">".
  5. "\\1\\3\\4</a>", $t);
  6.  
  7. // link mailtos
  8. $t = preg_replace( "/(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)".
  9. "([[:alnum:]-]))/i", "<a href=\"mailto:\\1\">\\1</a>", $t);
  10.  
  11. //link twitter users
  12. $t = preg_replace( "/ +@([a-z0-9_]*) ?/i", " <a href=\"http://twitter.com/\\1\" target=\"_blank\">@\\1</a> ", $t);
  13.  
  14. //link twitter arguments
  15. $t = preg_replace( "/ +#([a-z0-9_]*) ?/i", " <a href=\"http://twitter.com/search?q=%23\\1\" target=\"_blank\">#\\1</a> ", $t);
  16.  
  17. // truncates long urls that can cause display problems (optional)
  18. $t = preg_replace("/>(([[:alnum:]]+:\/\/)|www\.)([^[:space:]]".
  19. "{30,40})([^[:space:]]*)([^[:space:]]{10,20})([[:alnum:]#?\/&=])".
  20. "</", ">\\3...\\5\\6<", $t);
  21. return trim($t);
  22. }

URL: http://www.barattalo.it/2010/03/10/php-parse-url-mailto-and-also-twitters-usernames-and-arguments/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.