I noticed that most of my posts and projects have been quite centered around C# and application development instead of PHP and web development. To tell you the truth, I’m a little afraid of releasing my PHP code. Trust me, I write in true PHP 5 – very class oriented, none of this HTML intertwined between PHP code bull. It’s more that I want the code to be perfect before I release it. Starting now, I’ll try to share some useful functions I wrote that might help you on your quest to developing a PHP website.
Today, I’ll show you a quick function that converts time in words to seconds. Well, let’s say you are using memcached and you want to save an item for X seconds. It may be simple to put 60 for a minute or 3600 for a hour, but larger than that gets complex and not so easy to reverse (129600 is a day and a half). This function converts simple terms like “1d 6h” or “2h 24m 15s” to their seconds counterpart.
For the record, w = week, d = day, h = hour, m = minute, s = second.
-
/**
-
* This will convert from text like "2m 5s" to 125 seconds.
-
*/
-
function ttos($timeString) {
-
$seconds = 0;
-
-
$timeArray = explode(" ", $timeString);
-
$timeLength = count($timeArray);
-
-
for ($x = 0; $x < $timeLength; $x++) {
-
$type = substr($timeArray[$x], -1);
-
$value = substr($timeArray[$x], 0, -1);
-
-
if (is_numeric($value)) {
-
switch ($type) {
-
case "s":
-
$seconds += $value;
-
break;
-
case "m":
-
$seconds += $value * 60;
-
break;
-
case "h":
-
$seconds += $value * 3600;
-
break;
-
case "d":
-
$seconds += $value * 86400;
-
break;
-
case "w":
-
$seconds += $value * 630000;
-
break;
-
}
-
}
-
}
-
-
return $seconds;
-
}
If you think this function could be better, please drop me a comment. I’m always willing to improve!

