$string = '\n'; $string = 'Jon \'Maddog\' Orwant'; $string = 'Jon "Maddog" Orwant'; $string = "\n"; $string = "Jon \"Maddog\" Orwant"; $string = "Jon 'Maddog' Orwant"; $a =
"This is a multiline
here document";
$a = <<<EOF
This is a multiline here document
terminated by EOF on a line by itself
EOF;
$value = substr($string, $offset, $count);
$value = substr($string, $offset);
$string = substr_replace($string, $newstring, $offset, $count);
$string = substr_replace($string, $newtail, $offset);
list($leading, $s1, $s2, $trailing) =
array_values(unpack("A5a/x3/A8b/A8c/A*d", $data);
preg_match_all ("/.{5}/", $data, $f, PREG_PATTERN_ORDER);
$fivers = $f[0];
$chars = $string;
$string = "This is what you have";
$first = substr($string, 0, 1); $start = substr($string, 5, 2); $rest = substr($string, 13); $last = substr($string, -1); $end = substr($string, -4); $piece = substr($string, -8, 3); $string = "This is what you have";
print $string;
$string = substr_replace($string, "wasn't", 5, 2);
$string = substr_replace($string, "ondrous", -12);
$string = substr_replace($string, "", 0, 1);
$string = substr_replace($string, "", -10); if (preg_match("/pattern/", substr($string, -10)) {
print "Pattern matches in last 10 characters\n";
}
$string=(substr_replace(preg_replace("/is/", "at", substr($string,0,5)),0,5);
$a = "make a hat";
list($a[0], $a[strlen($a)-1]) = Array(substr($a,-1), substr($a,0,1));
print $a;
$a = "To be or not to be";
$b = unpack("x6/A6a", $a); print $b['a'];
$b = unpack("x6/A2b/X5/A2c", $a); print $b['b']."\n".$b['c']."\n";
function cut2fmt() {
$positions = func_get_args();
$template = '';
$lastpos = 1;
foreach($positions as $place) {
$template .= "A" . ($place - $lastpos) . " ";
$lastpos = $place;
}
$template .= "A*";
return $template;
}
$fmt = cut2fmt(8, 14, 20, 26, 30);
print "$fmt\n";
$a = $b?$b:$c;
$x || $x=$y;
$a = defined($b) ? $b : $c;
$foo = $bar || $foo = "DEFAULT VALUE";
$dir = array_shift($_SERVER['argv']) || $dir = "/tmp";
$dir = $_SERVER['argv'][0] || $dir = "/tmp";
$dir = defined($_SERVER['argv'][0]) ? array_shift($_SERVER['argv']) : "/tmp";
$dir = count($_SERVER['argv']) ? $_SERVER['argv'][0] : "/tmp";
$count[$shell?$shell:"/bin/sh"]++;
$user = $_ENV['USER']
|| $user = $_ENV['LOGNAME']
|| $user = posix_getlogin()
|| $user = posix_getpwuid(posix_getuid())[0]
|| $user = "Unknown uid number $<";
$starting_point || $starting_point = "Greenwich";
count($a) || $a = $b; $a = count($b) ? $b : $c;
list($VAR1, $VAR2) = array($VAR2, $VAR1);
$temp = $a;
$a = $b;
$b = $temp;
$a = "alpha";
$b = "omega";
list($a, $b) = array($b, $a); list($alpha, $beta, $production) = Array("January","March","August");
list($alpha, $beta, $production) = array($beta, $production, $alpha);
$num = ord($char);
$char = chr($num);
$char = sprintf("%c", $num); printf("Number %d is character %c\n", $num, $num);
$ASCII = unpack("C*", $string);
eval('$STRING = pack("C*", '.implode(',',$ASCII).');');
$ascii_value = ord("e"); $character = chr(101); printf("Number %d is character %c\n", 101, 101);
$ascii_character_numbers = unpack("C*", "sample");
print explode(" ",$ascii_character_numbers)."\n";
eval('$word = pack("C*", '.implode(',',$ascii_character_numbers).');');
$word = pack("C*", 115, 97, 109, 112, 108, 101); print "$word\n";
$hal = "HAL";
$ascii = unpack("C*", $hal);
foreach ($ascii as $val) {
$val++; }
eval('$ibm = pack("C*", '.implode(',',$ascii).');');
print "$ibm\n";
$array = preg_split('//', $string ,-1, PREG_SPLIT_NO_EMPTY);
for ($offset = 0; preg_match('/(.)/', $string, $matches, 0, $offset) > 0; $offset++) {
}
$seen = array();
$string = "an apple a day";
foreach (str_split($string) as $char) {
$seen[$char] = 1;
}
$keys = array_keys($seen);
sort($keys);
print "unique chars are: " . implode('', $keys)) . "\n";
unique chars are: adelnpy
$seen = array();
$string = "an apple a day";
for ($offset = 0; preg_match('/(.)/', $string, $matches, 0, $offset) > 0; $offset++) {
$seen[$matches[1]] = 1;
}
$keys = array_keys($seen);
sort($keys);
print "unique chars are: " . implode('', $keys) . "\n";
unique chars are: adelnpy
$sum = 0;
foreach (unpack("C*", $string) as $byteval) {
$sum += $byteval;
}
print "sum is $sum\n";
$sum = array_sum(unpack("C*", $string));
$handle = @fopen($argv[1], 'r');
$checksum = 0;
while (!feof($handle)) {
$checksum += (array_sum(unpack("C*", fgets($handle))));
}
$checksum %= pow(2,16) - 1;
print "$checksum\n";
<?php
$delay = 1;
if (preg_match('/(.)/', $argv[1], $matches)) {
$delay = $matches[1];
array_shift($argv);
};
$handle = @fopen($argv[1], 'r');
while (!feof($handle)) {
foreach (str_split(fgets($handle)) as $char) {
print $char;
usleep(5000 * $delay);
}
}
$revchars = strrev($string);
$revwords = implode(" ", array_reverse(explode(" ", $string)));
$string = 'Yoda said, "can you see this?"';
$allwords = explode(" ", $string);
$revwords = implode(" ", array_reverse($allwords));
print $revwords . "\n";
this?" see you "can said, Yoda
$revwords = implode(" ", array_reverse(explode(" ", $string)));
$revwords = implode(" ", array_reverse(preg_split("/(\s+)/", $string)));
$word = "reviver";
$is_palindrome = ($word === strrev($word));
% php -r 'while (!feof(STDIN)) { $word = rtrim(fgets(STDIN)); if ($word == strrev($word) && strlen($word) > 5) print $word; }' < /usr/dict/words
$text = preg_replace('/\$(\w+)/e', '$$1', $text);
list($rows, $cols) = Array(24, 80);
$text = 'I am $rows high and $cols long';
$text = preg_replace('/\$(\w+)/e', '$$1', $text);
print $text;
$text = "I am 17 years old";
$text = preg_replace('/(\d+)/e', '2*$1', $text);
$text = preg_replace('/\$(\w+)/e','isset($$1)?$$1:\'[NO VARIABLE: $$1]\'', $text);
$big = strtoupper($little);
$little = strtolower($big);
$big = ucfirst($little);
$little = strtolower(substr($big, 0, 1)) . substr($big, 1);
$beast = "dromedary";
$capit = ucfirst($beast); $capall = strtoupper($beast); $caprest = strtolower(substr($beast, 0, 1)) . substr(strtoupper($beast), 1); $text = "thIS is a loNG liNE";
$text = ucwords(strtolower($text));
print $text;
This Is A Long Line
if (strtoupper($a) == strtoupper($b)) { print "a and b are the same\n";
}
<?php
function randcase($word) {
return rand(0, 100) < 20 ? ucfirst($word) : lcfirst($word);
}
function lcfirst($word) {
return strtolower(substr($word, 0, 1)) . substr($word, 1);
}
while (!feof(STDIN)) {
print preg_replace("/(\w)/e", "randcase('\\1')", fgets(STDIN));
}
echo $var1 . func() . $var2; $answer = "STRING ${[ VAR EXPR ]} MORE STRING";
$phrase = "I have " . ($n + 1) . " guanacos.";
$output = wordwrap($str, $width, $break, $cut);
<?php
$input = "Folding and splicing is the work of an editor, " .
"not a mere collection of silicon " .
"and " .
"mobile electrons!";
$columns = 20;
print str_repeat("0123456789", 2) . "\n";
print wordwrap(' ' . $input, $columns - 3, "\n ") . "\n";
print wordwrap(str_replace("\n", " ", file_get_contents('php://stdin')));
while(!feof(STDIN)) {
print wordwrap(str_replace("\n", " ", stream_get_line(STDIN, 0, "\n\n")));
print "\n\n";
}
$var = preg_replace('/([CHARLIST])/', '\\\$1', $var);
$var = preg_replace('/([CHARLIST])/', '$1$1', $var);
$var = preg_replace('/%/', '%%', $var);
$string = 'Mom said, "Don\'t do that."';
$string = preg_replace('/([\'"])/', '\\\$1', $string);
$string = 'Mom said, "Don\'t do that."';
$string = preg_replace('/([\'"])/', '$1$1', $string);
$string = preg_replace('/([^A-Z])/', '\\\$1', $string);
$string = "this is\\ a\\ test\\!";
$string = preg_replace('/(\W)/', '\\\$1', 'is a test!');
$string = trim($string);
while (!feof(STDIN)) {
print ">" . substr(fgets(STDIN), 0, -1) . "<\n";
}
$string = preg_replace('/\s+/', ' ', $string); $string = trim($string);
$string = preg_replace('/\s+/', ' ', $string);
function sub_trim($string) {
$string = trim($string);
$string = preg_replace('/\s+/', ' ', $string);
return $string;
}
$code = soundex($string);
$phoned_words = metaphone("Schwern");
function getpwent() {
$pwents = array();
$handle = fopen("passwd", "r");
while (!feof($handle)) {
$line = fgets($handle);
if (preg_match("/^#/", $line)) continue;
$cols = explode(":", $line);
$pwents[$cols[0]] = $cols[4];
}
return $pwents;
}
print "Lookup user: ";
$user = rtrim(fgets(STDIN));
if (empty($user)) exit;
$name_code = soundex($user);
$pwents = getpwent();
foreach($pwents as $username => $fullname) {
preg_match("/(\w+)[^,]*\b(\w+)/", $fullname, $matches);
list(, $firstname, $lastname) = $matches;
if ($name_code == soundex($username) ||
$name_code == soundex($lastname) ||
$name_code == soundex($firstname))
{
printf("%s: %s %s\n", $username, $firstname, $lastname);
}
}
<?php
$data = <<<DATA
analysed=> analyzed
built-in=> builtin
chastized => chastised
commandline => command-line
de-allocate => deallocate
dropin => drop-in
hardcode=> hard-code
meta-data => metadata
multicharacter => multi-character
multiway=> multi-way
non-empty => nonempty
non-profit => nonprofit
non-trappable => nontrappable
pre-define => predefine
preextend => pre-extend
re-compiling=> recompiling
reenter => re-enter
turnkey => turn-key
DATA;
$scriptName = $argv[0];
$verbose = ($argc > 1 && $argv[1] == "-v" && array_shift($argv));
$change = array();
foreach (preg_split("/\n/", $data) as $pair) {
list($in, $out) = preg_split("/\s*=>\s*/", trim($pair));
if (!$in || !$out) continue;
$change[$in] = $out;
}
if (count($argv) > 1) {
$orig = $argv[1] . ".orig";
copy($argv[1], $orig);
$input = fopen($orig, "r");
$output = fopen($argv[1], "w");
} else if ($scriptName != "-") {
$input = STDIN;
trigger_error("$scriptName: Reading from stdin\n", E_USER_WARNING);
}
$ln = 1;
while (!feof($input)) {
$line = fgets($input);
foreach ($change as $in => $out) {
$line = preg_replace("/$in/", $out, $line, -1, $count);
if ($count > 0 && $verbose) {
fwrite(STDERR, "$in => $out at $argv[1] line $ln.\n");
}
}
@fwrite($output, $line);
$ln++;
}
<?php
$data = <<<DATA
analysed=> analyzed
built-in=> builtin
chastized => chastised
commandline => command-line
de-allocate => deallocate
dropin => drop-in
hardcode=> hard-code
meta-data => metadata
multicharacter => multi-character
multiway=> multi-way
non-empty => nonempty
non-profit => nonprofit
non-trappable => nontrappable
pre-define => predefine
preextend => pre-extend
re-compiling=> recompiling
reenter => re-enter
turnkey => turn-key
DATA;
$scriptName = $argv[0];
$verbose = ($argc > 1 && $argv[1] == "-v" && array_shift($argv));
if (count($argv) > 1) {
$orig = $argv[1] . ".orig";
copy($argv[1], $orig);
$input = fopen($orig, "r");
$output = fopen($argv[1], "w");
} else if ($scriptName != "-") {
$input = STDIN;
trigger_error("$scriptName: Reading from stdin\n", E_USER_WARNING);
}
$config = array();
foreach (preg_split("/\n/", $data) as $pair) {
list($in, $out) = preg_split("/\s*=>\s*/", trim($pair));
if (!$in || !$out) continue;
$config[$in] = $out;
}
$ln = 1;
while (!feof($input)) {
$i = 0;
preg_match("/^(\s*)(.*)/", fgets($input), $matches);
fwrite($output, $matches[1]);
foreach (preg_split("/(\s+)/", $matches[2], -1, PREG_SPLIT_DELIM_CAPTURE) as $token) {
fwrite($output, ($i++ & 1) ? $token : (array_key_exists($token, $config) ? $config[$token] : $token));
}
}
while (!feof($input)) {
$i = 0;
preg_match("/^(\s*)(.*)/", fgets($input), $matches); fwrite($output, $matches[1]);
foreach (preg_split("/(\s+)/", $matches[2]) as $token) { fwrite($output, (array_key_exists($token, $config) ? $config[$token] : $token) . " ");
}
fwrite($output, "\n");
}
under
$s = '12.345';
preg_match('/\D/', $s) && die("has nondigits\n");
preg_match('/^\d+$/', $s) || die("not a natural number\n");
preg_match('/^-?\d+$/', $s) || die("not an integer\n");
preg_match('/^[+-]?\d+$/', $s) || die("not an integer\n");
preg_match('/^-?\d+\.?\d*$/', $s) || die("not a decimal\n");
preg_match('/^-?(?:\d+(?:\.\d*)?|\.\d+)$/', $s) || die("not a decimal\n");
preg_match('/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/', $s) || die("not a C float\n");
function getnum($s)
{
sscanf($s, "%D", $number); return isset($number) ? $number : 0;
}
echo getnum(123) . "\n"; echo getnum(0xff) . "\n"; echo getnum(044) . "\n";
echo getnum('x') . "\n";
if ($float_1 == $float_2)
{
; }
$cmp = strcmp('123456789.123456789123456789', '123456789.123456789123456788');
$precision = 5; if (bccomp('1.111117', '1.111116', $precision))
{
; }
$precision = 6;
if (bccomp('1.111117', '1.111116', $precision))
{
; }
$wage = 536;
$week = $wage * 40;
printf("One week's wage is: $%.2f\n", $week / 100);
$rounded = round($unrounded, $precision);
$format = '%[width].[prec]f';
$rounded = sprintf($format, $unrounded);
$a = 0.255; $b = round($a, 2);
echo "Unrounded: {$a}\nRounded: {$b}\n";
$a = 0.255; $b = sprintf('%.2f', $a);
echo "Unrounded: {$a}\nRounded: {$b}\n";
$a = 0.255;
printf("Unrounded: %.f\nRounded: %.2f\n", $a, $a);
echo "number\tint\tfloor\tceil\n";
foreach(array(3.3, 3.5, 3.7, -3.3) as $number)
{
printf("%.1f\t%.1f\t%.1f\t%.1f\n", $number, (int) $number, floor($number), ceil($number));
}
$num = bindec('0110110');
$binstr = decbin(54);
foreach (range($X, $Y) as $i)
{
; }
foreach (range($X, $Y, 7) as $i)
{
; }
for ($i = $X; $i <= $Y; $i++)
{
; }
for ($i = $X; $i <= $Y; $i += 7)
{
; }
echo 'Infancy is:'; foreach(range(0, 2) as $i) echo " {$i}\n";
echo 'Toddling is:'; foreach(range(3, 4) as $i) echo " {$i}\n";
echo 'Childhood is:'; foreach(range(5, 12) as $i) echo " {$i}\n";
$roman = Numbers_Roman::toNumeral($arabic);
$arabic = Numbers_Roman::toNumber($roman);
$roman_fifteen = Numbers_Roman::toNumeral(15);
$arabic_fifteen = Numbers_Roman::toNumber($roman_fifteen);
printf("Roman for fifteen is: %s\n", $roman_fifteen);
printf("Arabic for fifteen is: %d\n", $arabic_fifteen);
$random = rand($lowerbound, $upperbound);
$random = rand($x, $y);
function make_password($chars, $reqlen)
{
$len = strlen($chars);
for ($i = 0; $i < $reqlen; $i++) $password .= substr($chars, rand(0, $len), 1);
return $password;
}
$chars = 'ABCDEfghijKLMNOpqrstUVWXYz'; $reqlen = 8;
$password = make_password($chars, $reqlen);
while (TRUE)
{
$seed = (int) fgets(STDIN);
if (!empty($seed)) break;
}
srand($seed);
mt_srand($saved_random_value + microtime() * 1000003);
mt_srand(($saved_random_value + hexdec(substr(md5(microtime()), -8))) & 0x7fffffff);
$truly_random_value = mt_rand();
function random() { return (float) rand() / (float) getrandmax(); }
function gaussian_rand()
{
$u1 = 0.0; $u2 = 0.0; $g1 = 0.0; $g2 = 0.0; $w = 0.0;
do
{
$u1 = 2.0 * random() - 1.0; $u2 = 2.0 * random() - 1.0;
$w = $u1 * $u1 + $u2 * $u2;
} while ($w > 1.0);
$w = sqrt((-2.0 * log($w)) / $w); $g2 = $u1 * $w; $g1 = $u2 * $w;
return $g1;
}
$mean = 25.0; $sdev = 2.0;
$salary = gaussian_rand() * $mean + $sdev;
printf("You have been hired at: %.2f\n", $salary);
/ them if needed
function deg2rad_($deg) { return ($deg / 180.0) * M_PI; }
function rad2deg_($rad) { return ($rad / M_PI) * 180.0; }
printf("%f\n", deg2rad_(180.0));
printf("%f\n", deg2rad(180.0));
function degree_sin($deg) { return sin(deg2rad($deg)); }
$rad = deg2rad(380.0);
printf("%f\n", sin($rad));
printf("%f\n", degree_sin(380.0));
function my_tan($theta) { return sin($theta) / cos($theta); }
$theta = 3.7;
printf("%f\n", my_tan($theta));
printf("%f\n", tan($theta));
$value = 100.0;
$log_e = log($value);
$log_10 = log10($value);
function log_base($base, $value) { return log($value) / log($base); }
$answer = log_base(10.0, 10000.0);
printf("log(10, 10,000) = %f\n", $answer);
$a = new Math_Matrix(array(array(3, 2, 3), array(5, 9, 8)));
$b = new Math_Matrix(array(array(4, 7), array(9, 3), array(8, 1)));
echo $a->toString() . "\n";
echo $b->toString() . "\n";
$c = $a->clone_();
$c->multiply($b);
echo $c->toString() . "\n";
$a = new Math_Complex(3, 5);
$b = new Math_Complex(2, -2);
$c = Math_ComplexOp::mult($a, $b);
echo $c->toString() . "\n";
$d = new Math_Complex(3, 4);
$r = Math_ComplexOp::sqrt($d);
echo $r->toString() . "\n";
$dec = 867;
$hex = sprintf('%x', $dec);
$oct = sprintf('%o', $dec);
$dec = 0;
$hex = '363';
sscanf($hex, '%x', $dec);
$dec = 0;
$oct = '1543';
sscanf($oct, '%o', $dec);
$number = 0;
printf('Gimme a number in decimal, octal, or hex: ');
sscanf(fgets(STDIN), '%D', $number);
printf("%d %x %o\n", $number, $number, $number);
function commify_series($s) { return number_format($s, 0, '', ','); }
$hits = 3456789;
printf("Your website received %s accesses last month\n", commify_series($hits));
function commify($s)
{
return strrev(preg_replace('/(\d\d\d)(?=\d)(?!\d*\.)/', '${1},', strrev($s)));
}
$hits = 3456789;
echo commify(sprintf("Your website received %d accesses last month\n", $hits));
function pluralise($value, $root, $singular='' , $plural='s')
{
return $root . (($value > 1) ? $plural : $singular);
}
$duration = 1;
printf("It took %d %s\n", $duration, pluralise($duration, 'hour'));
printf("%d %s %s enough.\n", $duration, pluralise($duration, 'hour'),
pluralise($duration, '', 'is', 'are'));
$duration = 5;
printf("It took %d %s\n", $duration, pluralise($duration, 'hour'));
printf("%d %s %s enough.\n", $duration, pluralise($duration, 'hour'),
pluralise($duration, '', 'is', 'are'));
function plural($singular)
{
$s2p = array('/ss$/' => 'sses', '/([psc]h)$/' => '${1}es', '/z$/' => 'zes',
'/ff$/' => 'ffs', '/f$/' => 'ves', '/ey$/' => 'eys',
'/y$/' => 'ies', '/ix$/' => 'ices', '/([sx])$/' => '$1es',
'$' => 's');
foreach($s2p as $s => $p)
{
if (preg_match($s, $singular)) return preg_replace($s, $p, $singular);
}
}
foreach(array('mess', 'index', 'leaf', 'puppy') as $word)
{
printf("%6s -> %s\n", $word, plural($word));
}
format
function dateOffset()
{
static $tbl = array('sec' => 1, 'min' => 60, 'hou' => 3600, 'day' => 86400, 'wee' => 604800);
$delta = 0;
foreach (func_get_args() as $arg)
{
$kv = explode('=', $arg);
$delta += $kv[1] * $tbl[strtolower(substr($kv[0], 0, 3))];
}
return $delta;
}
function dateInterval($intvltype, $timevalue)
{
static $tbl = array('sec' => 1, 'min' => 60, 'hou' => 3600, 'day' => 86400, 'wee' => 604800);
return (int) round($timevalue / $tbl[strtolower(substr($intvltype, 0, 3))]);
}
$today = getdate();
printf("Today is day %d of the current year\n", $today['yday']);
$today = localtime();
printf("Today is day %d of the current year\n", $today[7]);
$today = localtime(time(), TRUE);
printf("Today is day %d of the current year\n", $today['tm_yday']);
define(SEP, '-');
$today = getdate();
$day = $today['mday'];
$month = $today['mon'];
$year = $today['year'];
$sep = SEP;
echo "Current date is: {$year}{$sep}{$month}{$sep}{$day}\n";
echo 'Current date is: ' . $year . SEP . $month . SEP . $day . "\n";
$today = localtime(time(), TRUE);
$day = $today['tm_mday'];
$month = $today['tm_mon'] + 1;
$year = $today['tm_year'] + 1900;
printf("Current date is: %4d%s%2d%s%2d\n", $year, SEP, $month, SEP, $day);
$format = 'Y' . SEP . 'n' . SEP . 'd';
$today = date($format);
echo "Current date is: {$today}\n";
$sep = SEP;
$today = strftime("%Y$sep%m$sep%d");
echo "Current date is: {$today}\n";
$timestamp = mktime($hour, $min, $sec, $month, $day, $year);
$timestamp = gmmktime($hour, $min, $sec, $month, $day, $year);
$dmyhms = getdate();
$dmyhms = getdate($timestamp);
$day = $dmyhms['mday'];
$month = $dmyhms['mon'];
$year = $dmyhms['year'];
$hours = $dmyhms['hours'];
$minutes = $dmyhms['minutes'];
$seconds = $dmyhms['seconds'];
$when = $now + $difference;
$then = $now - $difference;
$now = mktime(0, 0, 0, 8, 6, 2003);
$diff1 = dateOffset('day=1'); $diff2 = dateOffset('weeks=2');
echo 'Today is: ' . date('Y-m-d', $now) . "\n";
echo 'One day in the future is: ' . date('Y-m-d', $now + $diff1) . "\n";
echo 'Two weeks in the past is: ' . date('Y-m-d', $now - $diff2) . "\n";
$birthtime = mktime(3, 45, 50, 1, 18, 1973);
$interval = dateOffset('day=55', 'hours=2', 'min=17', 'sec=5');
$then = $birthtime + $interval;
printf("Birthtime is: %s\nthen is: %s\n", date(DATE_RFC1123, $birthtime), date(DATE_RFC1123, $then));
$hr = 3; $min = 45; $sec = 50; $mon = 1; $day = 18; $year = 1973;
$yroff = 0; $monoff = 0; $dayoff = 55; $hroff = 2; $minoff = 17; $secoff = 5;
$birthtime = mktime($hr, $min, $sec, $mon, $day, $year, TRUE);
$year = date('Y', $birthtime) + $yroff;
$mon = date('m', $birthtime) + $monoff;
$day = date('d', $birthtime) + $dayoff;
$hr = date('H', $birthtime) + $hroff;
$min = date('i', $birthtime) + $minoff;
$sec = date('s', $birthtime) + $secoff;
$then = mktime($hr, $min, $sec, $mon, $day, $year, TRUE);
printf("Birthtime is: %s\nthen is: %s\n", date(DATE_RFC1123, $birthtime), date(DATE_RFC1123, $then));
$birthtime = mktime(3, 45, 50, 1, 18, 1973);
$birthtime = strtotime('1/18/1973 03:45:50');
$then = strtotime('+55 days 2 hours 17 minutes 2 seconds', $birthtime);
printf("Birthtime is: %s\nthen is: %s\n", date(DATE_RFC1123, $birthtime), date(DATE_RFC1123, $then));
$birthtime = new DateTime('1/18/1973 03:45:50');
$then = new DateTime('1/18/1973 03:45:50');
$then->modify('+55 days 2 hours 17 minutes 2 seconds');
printf("Birthtime is: %s\nthen is: %s\n", $birthtime->format(DATE_RFC1123), $then->format(DATE_RFC1123));
$interval_seconds = $recent - $earlier;
$bree = strtotime('16 Jun 1981, 4:35:25');
$nat = strtotime('18 Jan 1973, 3:45:50');
$bree = mktime(4, 35, 25, 6, 16, 1981, TRUE);
$nat = mktime(3, 45, 50, 1, 18, 1973, TRUE);
$difference = $bree - $nat;
printf("There were %d seconds between Nat and Bree\n", $difference);
printf("There were %d weeks between Nat and Bree\n", dateInterval('weeks', $difference));
printf("There were %d days between Nat and Bree\n", dateInterval('days', $difference));
printf("There were %d hours between Nat and Bree\n", dateInterval('hours', $difference));
printf("There were %d minutes between Nat and Bree\n", dateInterval('mins', $difference));
$today = getdate();
$weekday = $today['wday'];
$monthday = $today['mday'];
$yearday = $today['yday'];
$weeknumber = (int) round($yearday / 7.0);
$weeknumber = strftime('%U') + 1;
define(SEP, '/');
$day = 16;
$month = 6;
$year = 1981;
$timestamp = mktime(0, 0, 0, $month, $day, $year);
$date = getdate($timestamp);
$weekday = $date['wday'];
$monthday = $date['mday'];
$yearday = $date['yday'];
$weeknumber = (int) round($yearday / 7.0);
$weeknumber = strftime('%U', $timestamp) + 1;
$sep = SEP;
echo "{$month}{$sep}{$day}{$sep}{$year} was a {$date['weekday']} in week {$weeknumber}\n";
echo $month . SEP . $day . SEP . $year . ' was a ' . $date['weekday']
. ' in week ' . $weeknumber . "\n";
$timestamp = strtotime('1998-06-03'); echo strftime('%Y-%m-%d', $timestamp) . "\n";
print_r(strptime('1998-06-03', '%Y-%m-%d'));
$darr = strptime('1998-06-03', '%Y-%m-%d');
if (!empty($darr))
{
print_r($darr);
if (empty($darr['unparsed']))
{
if (checkdate($darr['tm_mon'] + 1, $darr['tm_mday'], $darr['tm_year'] + 1900))
echo "Parsed date verified as correct\n";
else
echo "Parsed date failed verification\n";
}
else
{
echo "Date string parse not complete; failed components: {$darr['unparsed']}\n";
}
}
else
{
echo "Date string could not be parsed\n";
}
$ts = 1234567890;
date('Y/m/d', $ts);
date('Y/m/d', mktime($h, $m, $s, $mth, $d, $y, $is_dst));
date('Y/m/d');
$ts = 1234567890;
strftime('%Y/%m/%d', $ts);
strftime('%Y/%m/%d', mktime($h, $m, $s, $mth, $d, $y, $is_dst));
strftime('%Y/%m/%d');