• 0

Twitter Widget in PHP


Question

So, I've successfully gotten a Twitter widget to work, but there's a problem with the preg_replace on the first $ret. These variables are obviously created to find links and hash tags. The first one was meant to detect http:// links and the second one is for www and ftp.

If you test it out and hover your mouse over a link on the latest tweet, you'll notice that there's "http//" instead of "http://".

Can I get a little help on that please? :)

<?php
function getLastXTwitterStatus($userid,$x){
$url = "http://twitter.com/statuses/user_timeline/$userid.xml?count=$x&quot";
$xml = simplexml_load_file($url) or die('could not connect');
echo '<ul>';
	   foreach($xml->status as $status){
	   $text = twitterify( $status->text );
	echo '<li>'.utf8_decode($text).'</li>';
	   }
	echo '</ul>';
}
function twitterify($ret) {
  $ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"http://\\2\" >\\2</a>", $ret);
  $ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" >\\2</a>", $ret);
  $ret = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" >@\\1</a>", $ret);
  $ret = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" >#\\1</a>", $ret);
return $ret;
}
getLastXTwitterStatus('IllingSpree',2);
?>

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

Your first regex is a bit borked, try this one instead (I use it myself and have done from some time in a Twitter app I wrote)...

    $ret = preg_replace('@(https?://([-\w\.]+)+(/([\w/_\-\.]*(\?\S+)?(#\S+)?)?)?)@','<a href="$1">$1</a>',$ret);

Link to comment
Share on other sites

  • 0

Appreciate it broski!

Is there an alternative to the "or die" method? Because we all know it kills all the code that comes after it.

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

Link to comment
Share on other sites

  • 0

Appreciate it broski!

Is there an alternative to the "or die" method? Because we all know it kills all the code that comes after it.

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

NP mate.

If it can't connect the code after it can't continue anyway, if you want to do something else other than die just code it in an if / else block statement...


if ($xml = simplexml_load_file($url)) {
    // existing code here ....
} else {
    // handle failure here ...
}

Link to comment
Share on other sites

  • 0

I should of known the if statement would've been the best method for the fact that I'm always looking at if's on WordPress' template. :huh:

Works flawlessly of course. :)

Thanks again! :D

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.