Awhile back, I posted a modification to the Twitget Twitter widget I’m now using to display my tweets over there on the side bar. I’ve now made some further improvements since my original changes made an erroneous assumption about processing the tweet information.
First, hashtag links were losing the leading space when being displayed in the sidebar. The fix here was trivial, as it simply requires adding a space to the to preg_replace
function calls in the process_links
function that deal with generating the hashtag links.
The second fix is slightly more significant. Basically, if there are no URL entities in the tweet metadata, then the code needs to find link text within the tweet and turn it into a link. Here’s the new batch of code:
function process_links($text, $new, $urls) {
if($new) {
$linkmarkup = '<a rel="nofollow" target="_blank" href="';
$text = preg_replace('/@(\w+)/', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $text);
$text = preg_replace('/\s#(\w+)/', ' <a href="http://twitter.com/search?q=%23$1&src=hash" target="_blank">#$1</a>', $text);
}
else {
$linkmarkup = '<a rel="nofollow" href="';
$text = preg_replace('/@(\w+)/', '<a href="http://twitter.com/$1">@$1</a>', $text);
$text = preg_replace('/\s#(\w+)/', ' <a href="http://twitter.com/search?q=%23$1&src=hash">#$1</a>', $text);
}
if (!empty($urls))
foreach($urls as $url) {
$find = $url['url'];
$replace = $linkmarkup.$find.'">'.$url['expanded_url'].'</a>';
$text = str_replace($find, $replace, $text);
}
else {
if ($new) {
$text = preg_replace('@(https?://([-\w\.]+)+(d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1" target="_blank">$1</a>', $text);
}
else {
$text = preg_replace('@(https?://([-\w\.]+)+(d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $text);
}
}
return $text;
}
The framework here is pretty much identical as before. The main addition is the else
clause in the if(!empty($urls))
. The code after that is actually the previous link code- regexes like that are too persnickety to reinvent.
So this will suffice until the next problems surfaces.