Last active
November 21, 2015 13:03
-
-
Save TangChr/11175443 to your computer and use it in GitHub Desktop.
PHP: Convert hastags, mentions & URLs to hyperlinks in a tweet.
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 | |
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; | |
?> |
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 | |
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