This function emulates PHP’s wordwrap. It takes four arguments:
- The string to be wrapped.
- The column width (a number, default: 75)
- The character(s) to be inserted at every break. (default: ‘\n’)
- The cut: a Boolean value (false by default). See PHP docs for more info.
The code
function wordwrap( str, width, brk, cut ) {
brk = brk || '\n';
width = width || 75;
cut = cut || false;
if (!str) { return str; }
var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
return str.match( RegExp(regex, 'g') ).join( brk );
}
Usage
wordwrap('The quick brown fox jumped over the lazy dog.', 20, '<br/>\n');
The quick brown fox <br/>
jumped over the lazy <br/>
dog.
I know there are other solutions out there; the ones I saw seemed a bit slow though, not to mention unnecessarily complicated/bloated…
This recently created PHP class is part of today’s ongoing struggle of trying to create a Twitter ‘drip’ that will automatically update Twitter at pre-defined intervals with status updates specified in a text file.
// (C) Copyright JAMES PADOLSEY
class tweetFromFile {
private $curlHandle;
private $updateFile;
private $archiveFile;
private function getNewStatus() {
$upcomingTweetsFile = $this->files['upcoming'];
$archivedTweetsFile = $this->files['archive'];
$upcomingTweets_R = fopen($upcomingTweetsFile, "r");
// Get upcoming Tweets:
$contents = fread($upcomingTweets_R, filesize($upcomingTweetsFile));
$splitContents = preg_split('/\n/', $contents, 2);
// ARCHIVE OLD POSTS:
$archive = fopen($archivedTweetsFile, "a");
fwrite($archive, $splitContents[0]."\n");
// Remove top line from upcoming:
$upcomingTweets_W = fopen($upcomingTweetsFile, "w");
fwrite($upcomingTweets_W, $splitContents[1]);
// Clean up
fclose($upcomingTweets_W);
fclose($upcomingTweets_R);
fclose($archive);
return $splitContents[0];
}
public $files = array('upcoming' => '', 'archive' => '');
public function __construct($username, $password, $filename) {
$this->curlHandle = curl_init();
$this->files['upcoming'] = $filename;
$this->files['archive'] = 'ARCHIVE_' . $filename;
// Shortcut:
$ch = $this->curlHandle;
curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/update.xml");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
}
public function __destruct() {
curl_close($this->curlHandle);
}
public function updateStatus() {
$status = $this->getNewStatus();
curl_setopt($this->curlHandle, CURLOPT_POSTFIELDS, "status=$status");
$result = curl_exec($this->curlHandle);
$resultArray = curl_getinfo($this->curlHandle);
if ($resultArray['http_code'] == 200) return true;
return false;
}
}
// ==================
// ===== USAGE ======
// ==================
$tweet = new tweetFromFile('twitterUsername', 'password', 'textfile.txt');
$success = $tweet->updateStatus();
if ($success) {
echo 'Twitter updated!';
} else {
echo 'Hmm, an error...';
}
The class will retrieve each new update from the specified text file. Each update needs to be on a new line; an example text file:
Blah blah blah, this is the first update...
And another update!
Third and last update!!! ARGH!
The PHP class will remove each update from this file when it’s added to Twitter so all you need to do is keep adding to the bottom of the file…
This won’t do the dripping automatically. You’ll need to setup a ‘cron job’ to request the script at selected intervals (e.g. every two hours). I’m rubbish at Apache and anything to do with the command line so I haven’t quite accomplished this part yet… maybe someone else wants to give it a go?
Getting the time in JavaScript is pretty simple. Using the Date constructor will give us the time as set on the user’s computer, but what if we want the accurate time, or the time in a different timezone?
Even with getTimezoneOffset() you’re still relying on the client!
It turns out that the only way of getting a complete and accurate time from any timezone requires a little bit of server interaction. Luckily there are a few APIs out there that offer this service (actually, there’s only one; well I couldn’t find any others)!
Here we’re using the ‘json-time’ API developed by Simon Willson:
JSON-time
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime), o);
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
Usage
The first parameter of the callback function is the time (having been passed through the Date constructor), so you can use Date methods such as getSeconds() etc. The second parameter is the entire object returned from the JSON request.
// Alert GMT:
getTime('GMT', function(time){
alert(time);
});
// Get London time, and format it:
getTime('Europe/London', function(time){
var formatted = time.getHours() + ':'
+ time.getMinutes() + ':'
+ time.getSeconds();
alert( 'The time in London is ' + formatted );
});
For reference, here’s a list of all the available timezones (to use one, remove the backslash).
jQuery version
$.getTime = function(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz='
+ zone + '&callback=?';
$.getJSON(url, function(o){
success && success(new Date(o.datetime), o);
});
};
// Usage:
$.getTime('GMT', function(time){
alert(time);
});
MooTools version
You’ll need to download the JsonP class.
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json';
new JsonP(url, {
data: { tz: zone },
onComplete: function(o){
success && success(new Date(o.datetime), o);
}
}).request();
}
// Usage:
getTime('GMT', function(time){
alert(time);
});
Thank you Simon Willison for making this API; seriously, I searched around the entire internets just for one damn API and I almost lost hope!
Here’s a very handy script which will scan through a directory of images, form an array of the contents of that directory and then return the array in JSON format to the client-side where the images will be preloaded into the user’s cache.
There are two components to this: the PHP script and some simple JavaScript: