Last active
September 28, 2017 01:08
-
-
Save robinbentley/5772791 to your computer and use it in GitHub Desktop.
Pull out links, usernames and hashtags from a plaintext tweet. I imagine there is a cleaner way (regex is not my thing) but it works well at getting what's needed.
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 | |
// Find normal links, wrap with anchor tags and add href to link | |
$tweet = preg_replace('/(https?:\/\/[^\s"<>]+)/','<a href="$1">$1</a>',$tweet); | |
// Find usernames, wrap with anchor and add href to their profile | |
$tweet = preg_replace('/(^|[\n\s])@([^\s"\t\n\r<:]*)/is', '$1<a href="http://twitter.com/$2">@$2</a>', $tweet); | |
// Find hashtags, wrap with anchor and add href to twitter search for that tag | |
$tweet = preg_replace('/(^|[\n\s])#([^\s"\t\n\r<:]*)/is', '$1<a href="http://twitter.com/search?q=%23$2">#$2</a>', $tweet); | |
echo $tweet; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment