Posted By

SFLWebDev on 06/08/11


Tagged

twitter


Versions (?)

Parse Twitter


 / Published in: PHP
 

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

Text parsing for Twitter text attribute - segregating and styling output for link URLs, link mailtos, Twitter users (@ replies), Twitter arguments, and truncation for long URLs.

  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. }

Report this snippet  

You need to login to post a comment.