Skip to content

Instantly share code, notes, and snippets.

@TangChr
Last active November 21, 2015 13:03
Show Gist options
  • Save TangChr/11175443 to your computer and use it in GitHub Desktop.
Save TangChr/11175443 to your computer and use it in GitHub Desktop.
PHP: Convert hastags, mentions & URLs to hyperlinks in a tweet.
<?php
require 'tweet_parser.php';
$userUrl = 'https://twitter.com/';
$tagUrl = 'https://twitter.com/hashtag/';
$my_tweet = "@TangChr: Here's a link: http://willitcompile.net, and here's a #hashtag.";
$formatted = parseTweet($my_tweet, $userUrl, $tagUrl);
$formatted2 = parseTweetPrefix($my_tweet, $userUrl, $tagUrl);
echo <<<HTML
<p>$my_tweet</p>
<p><strong>Excl. prefix:</strong> $formatted</p>
<p><strong>Incl. prefix:</strong> $formatted2</p>
HTML;
?>
<?php
function parseTweet($tweet, $userUrl, $tagUrl) {
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", '<a class="tweet-link" href=\"\0">\0</a>', $tweet); // Hyperlinks
$text = preg_replace('/(^|\s)@(\w+)/','\1@<a class="tweet-username" href="'.$userUrl.'\2">\2</a>',$text); // Usernames
$text = preg_replace('/(^|\s)#(\w+)/','\1#<a class="tweet-tag" href="'.$tagUrl.'\2">\2</a>',$text); // Hashtags
return $text;
}
// Include prefix (#, @) in link-text.
function parseTweetPrefix($tweet, $userUrl, $tagUrl) {
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", '<a class="tweet-link" href=\"\0">\0</a>', $tweet); // Hyperlinks
$text = preg_replace('/(^|\s)@(\w+)/','\1<a class="tweet-username" href="'.$userUrl.'\2">@\2</a>',$text); // Usernames
$text = preg_replace('/(^|\s)#(\w+)/','\1<a class="tweet-tag" href="'.$tagUrl.'\2">#\2</a>',$text); // Hashtags
return $text;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment