Skip to content

Instantly share code, notes, and snippets.

@crittermike
Created June 24, 2014 15:07
Show Gist options
  • Save crittermike/6a24108a65407676497e to your computer and use it in GitHub Desktop.
Save crittermike/6a24108a65407676497e to your computer and use it in GitHub Desktop.
Parse a tweet's text with PHP and regex
<?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