<?php
// words-to-number-converter
// Source: https://github.com/thefish/words-to-number-converter
// License: MIT
// Original author: thefish
//
// This file is copied for use in JCOGS Image Pro DurationParser

/*
 * Converts number words to numbers, e.g. "eight days" => "8 days"
 * Usage: wordsToNumber($string)
 */

function wordsToNumber($words) {
    $words = strtolower($words);
    $numwords = array(
        'zero' => 0,
        '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,
        'fifty' => 50,
        'sixty' => 60,
        'seventy' => 70,
        'eighty' => 80,
        'ninety' => 90,
        'hundred' => 100,
        'thousand' => 1000,
        'million' => 1000000,
        'billion' => 1000000000,
    );
    $words = preg_replace('/\band\b/', '', $words);
    $words = preg_replace('/\s+/', ' ', $words);
    $parts = explode(' ', $words);
    $total = 0;
    $current = 0;
    foreach ($parts as $part) {
        if (isset($numwords[$part])) {
            $scale = $numwords[$part];
            if ($scale >= 100) {
                if ($current == 0) $current = 1;
                $current *= $scale;
            } else {
                $current += $scale;
            }
        } else if (is_numeric($part)) {
            $current += (int)$part;
        } else {
            if ($current > 0) {
                $total += $current;
                $words = preg_replace('/\b' . $part . '\b/', $total, $words, 1);
                $current = 0;
                $total = 0;
            }
        }
    }
    if ($current > 0) {
        $words = preg_replace('/\b' . $parts[count($parts)-1] . '\b/', $current, $words, 1);
    }
    return $words;
}
