views:

23

answers:

2

I've got a nice little twitter widget on my website that was created using php. I'd like to be able to make sure that when a link appears it is clickable or when I @reply someone it links to their profile. Any help is greatly appreciated.

<?php

function getTwitterStatus($userid){
$url = "http://twitter.com/statuses/user_timeline/$userid.xml?count=1";

$xml = simplexml_load_file($url) or die("could not connect");

       foreach($xml->status as $status){
       $text = $status->text;
       }
       echo $text;
 }

getTwitterStatus("UltanKC");

?>
A: 

Looks like this one is pretty comprehensive via googling 'twitter php automatic links'

(from http://www.snipe.net/2009/09/php-twitter-clickable-links/):

function twitterify($ret) {
    $ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
    $ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret);
    $ret = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $ret);
    $ret = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $ret);
    return $ret;
}
AvatarKava
+1  A: 

I have a function which I use for this - it will make links for URLs, twitter user names and twitter hashtags.

function auto_link_twitter ($text)
{
    // properly formatted URLs
    $urls = "/(((http[s]?:\/\/)|(www\.))?(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1})/is";
    $text = preg_replace($urls, " <a href='$1'>$1</a>", $text);

    // URLs without protocols
    $text = preg_replace("/href=\"www/", "href=\"http://www", $text);

    // Twitter usernames
    $twitter = "/@([A-Za-z0-9_]+)/is";
    $text = preg_replace ($twitter, " <a href='http://twitter.com/$1'&gt;@$1&lt;/a&gt;", $text);

    // Twitter hashtags
    $hashtag = "/#([A-Aa-z0-9_-]+)/is";
    $text = preg_replace ($hashtag, " <a href='http://hashtags.org/$1'&gt;#$1&lt;/a&gt;", $text);
    return $text;
}

to use it with your code, edit the line which echoes out the status:

echo auto_link_twitter ($text);
slightlymore
Where do I insert the larger function piece of the code? Do i replace echo $text; } with echo auto_link_twitter ($text);
ThatMacLad
I got it working. I was being a bit noobish. Thanks!
ThatMacLad