Last active
March 24, 2016 16:24
-
-
Save styledev/3337428 to your computer and use it in GitHub Desktop.
This function will linkify your tweet messages from the Twitter API using include_entities=true
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
function parse_message( &$tweet ) { | |
if ( !empty($tweet['entities']) ) { | |
$replace_index = array(); | |
$append = array(); | |
$text = $tweet['text']; | |
foreach ($tweet['entities'] as $area => $items) { | |
$prefix = false; | |
$display = false; | |
switch ( $area ) { | |
case 'hashtags': | |
$find = 'text'; | |
$prefix = '#'; | |
$url = 'https://twitter.com/search/?src=hash&q=%23'; | |
break; | |
case 'user_mentions': | |
$find = 'screen_name'; | |
$prefix = '@'; | |
$url = 'https://twitter.com/'; | |
break; | |
case 'media': | |
$display = 'media_url_https'; | |
$href = 'media_url_https'; | |
$size = 'small'; | |
break; | |
case 'urls': | |
$find = 'url'; | |
$display = 'display_url'; | |
$url = "expanded_url"; | |
break; | |
default: break; | |
} | |
foreach ($items as $item) { | |
if ( $area == 'media' ) { | |
// We can display images at the end of the tweet but sizing needs to added all the way to the top. | |
// $append[$item->$display] = "<img src=\"{$item->$href}:$size\" />"; | |
}else{ | |
$msg = $display ? $prefix.$item->$display : $prefix.$item->$find; | |
$replace = $prefix.$item->$find; | |
$href = isset($item->$url) ? $item->$url : $url; | |
if (!(strpos($href, 'http') === 0)) $href = "http://".$href; | |
if ( $prefix ) $href .= $item->$find; | |
$with = "<a href=\"$href\">$msg</a>"; | |
$replace_index[$replace] = $with; | |
} | |
} | |
} | |
foreach ($replace_index as $replace => $with) $tweet['text'] = str_replace($replace,$with,$tweet['text']); | |
foreach ($append as $add) $tweet['text'] .= $add; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PHP n00b here. Shouldn't I be able to just add this to my code and it work? Or do I have to implement it into my existing code? I have a page that retrieves tweets, like a custom widget. How do I use this to make the entities links, as it should? Put it in my page and nothing happens.