Here is a function that converts hashtags, custom links, and URLs into links using entity data in a tweet from the Twitter API.
<?php
function tweet_html_text(array $tweet) {
$text = $tweet['text'];
$linkified = array();
foreach ($tweet['entities']['hashtags'] as $hashtag) {
$hash = $hashtag['text'];
if (in_array($hash, $linkified)) {
continue;
}
$linkified[] = $hash;
$text = preg_replace('/#\b' . $hash . '\b/', sprintf('<a href="https://twitter.com/search?q=%%23%2$s&src=hash">#%1$s</a>', $hash, urlencode($hash)), $text);
}
$linkified = array();
foreach ($tweet['entities']['user_mentions'] as $userMention) {
$name = $userMention['name'];
$screenName = $userMention['screen_name'];
if (in_array($screenName, $linkified)) {
continue;
}
$linkified[] = $screenName;
$text = preg_replace('/@\b' . $screenName . '\b/', sprintf('<a href="https://www.twitter.com/%1$s" title="%2$s">@%1$s</a>', $screenName, $name), $text);
}
$linkified = array();
foreach ($tweet['entities']['urls'] as $url) {
$url = $url['url'];
if (in_array($url, $linkified)) {
continue;
}
$linkified[] = $url;
$text = str_replace($url, sprintf('<a href="%1$s">%1$s</a>', $url), $text);
}
return $text;
}
source
share