I\'m really stumped on how Twitter expects users of its API to convert the plaintext tweets it sends to properly linked HTML.
Here\'s the deal: Twitter\'s JSON API sends
It's an edge case but the use of str_replace() in Styledev's answer could cause issues if one entity is contained within another. For example, "I'm a genius! #me #mensa" could become "I'm a genius! #me #mensa" if the shorter entity is substituted first.
This solution avoids that problem:
text);
$characters = preg_split('//u', $apiResponseTweetObject->text, null, PREG_SPLIT_NO_EMPTY);
// Insert starting and closing link tags at indices...
// ... for @user_mentions
foreach ($apiResponseTweetObject->entities->user_mentions as $entity) {
$link = "https://twitter.com/" . $entity->screen_name;
$characters[$entity->indices[0]] = "" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "";
}
// ... for #hashtags
foreach ($apiResponseTweetObject->entities->hashtags as $entity) {
$link = "https://twitter.com/search?q=%23" . $entity->text;
$characters[$entity->indices[0]] = "" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "";
}
// ... for http://urls
foreach ($apiResponseTweetObject->entities->urls as $entity) {
$link = $entity->expanded_url;
$characters[$entity->indices[0]] = "" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "";
}
// ... for media
foreach ($apiResponseTweetObject->entities->media as $entity) {
$link = $entity->expanded_url;
$characters[$entity->indices[0]] = "" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "";
}
// Convert array back to string
return implode('', $characters);
}
?>