Skip to content

Instantly share code, notes, and snippets.

@syntaqx
Last active May 2, 2023 20:56
Show Gist options
  • Save syntaqx/d932e3dec9dad98f13f49d7bac8d6e6a to your computer and use it in GitHub Desktop.
Save syntaqx/d932e3dec9dad98f13f49d7bac8d6e6a to your computer and use it in GitHub Desktop.
<?php
$unknown_format = [
'2023/05/02',
'05/02/2023',
];
foreach ($unknown_format as $fmt) {
echo date("Y-m-d", strtotime($fmt)) . PHP_EOL;
}
<?php
/**
* Convert a string such as "one hundred thousand" to 100000.00.
*
* @param string $data The numeric string.
* @return float or false on error
*/
function wordsToNumber($data) {
// Replace all number words with an equivalent numeric value
$data = strtr(
$data,
array(
'zero' => '0',
'a' => '1',
'one' => '1',
'two' => '2',
'three' => '3',
'four' => '4',
'five' => '5',
'six' => '6',
'seven' => '7',
'eight' => '8',
'nine' => '9',
'ten' => '10',
'eleven' => '11',
'twelve' => '12',
'thirteen' => '13',
'fourteen' => '14',
'fifteen' => '15',
'sixteen' => '16',
'seventeen' => '17',
'eighteen' => '18',
'nineteen' => '19',
'twenty' => '20',
'thirty' => '30',
'forty' => '40',
'fourty' => '40', // EU spelling
'fifty' => '50',
'sixty' => '60',
'seventy' => '70',
'eighty' => '80',
'ninety' => '90',
'hundred' => '100',
'thousand' => '1000',
'million' => '1000000',
'billion' => '1000000000',
'and' => '',
)
);
// Coerce all tokens to numbers
$parts = array_map(
function ($val) {
return floatval($val);
},
preg_split('/[\s-]+/', $data)
);
$stack = new SplStack;
$sum = 0;
$last = null;
foreach ($parts as $part) {
if (!$stack->isEmpty()) {
if ($stack->top() > $part) {
if ($last >= 1000) {
$sum += $stack->pop();
$stack->push($part);
} else {
$stack->push($stack->pop() + $part);
}
} else {
$stack->push($stack->pop() * $part);
}
} else {
$stack->push($part);
}
$last = $part;
}
return $sum + $stack->pop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment