Skip to content

Instantly share code, notes, and snippets.

@danwaz
Last active December 20, 2015 04:49
Show Gist options
  • Save danwaz/6073210 to your computer and use it in GitHub Desktop.
Save danwaz/6073210 to your computer and use it in GitHub Desktop.
Format Tweet PHP
<?php
function format_tweet($tweet_obj){
//create an array of tweet entities
$entity_arr = array();
$formatted_text = $tweet_obj['text'];
foreach($tweet_obj['entities'] as $entity){
foreach($entity as $item){
$entity_arr[] = $item;
}
}
//sort entity indices from largest to smallest
//this allows you to modify the original text without worrying about indices changing
usort($entity_arr, 'indices_sort');
//format it!
for($i = 0; $i < count($entity_arr); $i++){
$target_text = substr($formatted_text, $entity_arr[$i]['indices'][0], $entity_arr[$i]['indices'][1] - $entity_arr[$i]['indices'][0]);
if($entity_arr[$i]['screen_name']){
$formatted_text = str_replace($target_text, '<a href="http://twitter.com/'. $entity_arr[$i]['screen_name'] .'" target="_blank">'. $target_text .'</a>', $formatted_text);
} else if ($entity_arr[$i]['url']) {
$formatted_text = str_replace($target_text, '<a href="'. $target_text .'" target="_blank">'. $target_text .'</a>', $formatted_text);
} else {
$formatted_text = str_replace($target_text, '<a href="http://twitter.com/hashtag/'. $entity_arr[$i]['text'] .'" target="_blank">'. $target_text .'</a>', $formatted_text);
}
}
return $formatted_text;
}
//sorting function used for sorting tweets
function indices_sort($a, $b){
if(intval($b['indices'][0]) == intval($a['indices'][0])){
return 0;
}
return (intval($b['indices'][0]) < intval($a['indices'][0])) ? -1 : 1;
}
function format_time($time_to_format){
$current_time = time();
$time_to_format = strtotime($time_to_format);
$time_ago = $current_time - $time_to_format;
$formatted_time = '';
if($time_ago < 60){
$formatted_time = $time_ago . ' seconds ago';
} else if($time_ago < 3600){
$formatted_time = floor($time_ago/60) . (floor($time_ago/60) == 1 ? ' minute ago' : ' minutes ago');
} else if($time_ago < 86400) {
$formatted_time = floor($time_ago/3600) . (floor($time_ago/3600) == 1 ? ' hour ago' : ' hours ago');
} else if($time_ago > 86400){
$formatted_time = floor($time_ago/86400) . (floor($time_ago/86400) == 1 ? ' day ago' : ' days ago');
}
return $formatted_time;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment