Created
June 24, 2014 15:07
-
-
Save crittermike/6a24108a65407676497e to your computer and use it in GitHub Desktop.
Parse a tweet's text with PHP and regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Regex taken from http://saturnboy.com/2010/02/parsing-twitter-with-regexp/ | |
*/ | |
function parse_tweet($text) { | |
// Parse links. | |
$text = preg_replace( | |
'@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@', | |
'<a href="$1">$1</a>', | |
$text); | |
// Parse @mentions | |
$text = preg_replace( | |
'/@(\w+)/', | |
'<a href="http://twitter.com/$1">@$1</a>', | |
$text); | |
// Parse #hashtags | |
$text = preg_replace( | |
'/\s+#(\w+)/', | |
' <a href="http://search.twitter.com/search?q=%23$1">#$1</a>', | |
$text); | |
return $text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment