本文介绍了在 php 中将单词转换为数字 II的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一个很棒的功能在 PHP 中将单词转换为数字来自埃尔约博.但是我遇到了字符串必须以书面数字开头的问题.如何转换例如iPhone 有二十三万,七百八十三款应用"?

There is a great function here Converting words to numbers in PHP from El Yobo.But I have the problem that the string must begin with a written number.How can convert e.g. "iPhone has two hundred and thirty thousand, seven hundred and eighty-three apps" ?

解释函数:

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', // common misspelling
        '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; // Current work stack
$sum   = 0; // Running total
$last  = null;

foreach ($parts as $part) {
    if (!$stack->isEmpty()) {
        // We're part way through a phrase
        if ($stack->top() > $part) {
            // Decreasing step, e.g. from hundreds to ones
            if ($last >= 1000) {
                // If we drop from more than 1000 then we've finished the phrase
                $sum += $stack->pop();
                // This is the first element of a new phrase
                $stack->push($part);
            } else {
                // Drop down from less than 1000, just addition
                // e.g. "seventy one" -> "70 1" -> "70 + 1"
                $stack->push($stack->pop() + $part);
            }
        } else {
            // Increasing step, e.g ones to hundreds
            $stack->push($stack->pop() * $part);
        }
    } else {
        // This is the first element of a new phrase
        $stack->push($part);
    }

    // Store the last processed part
    $last = $part;
}

return $sum + $stack->pop();
}

推荐答案

好吧..我不得不承认..这对我个人来说很有趣!!!无论如何......这是代码......你可以在这里测试它:http://www.eyerollweb.com/str2digits/

Well .. i have to admit.. this was interesting to me on a personal level !!! anyway ... here is the code... you can test it here : http://www.eyerollweb.com/str2digits/

这里是代码本身:

<?php

//The Test string
$str = "two hundred thousand six hundred and two";

$numbers = 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,
    'fourty' => 40, // common misspelling
    'fifty' => 50,
    'sixty' => 60,
    'seventy' => 70,
    'eighty' => 80,
    'ninety' => 90,
    'hundred' => 100,
    'thousand' => 1000,
    'million' => 1000000,
    'billion' => 1000000000);

//first we remove all unwanted characters... and keep the text
$str = preg_replace("/[^a-zA-Z]+/", " ", $str);

//now we explode them word by word... and loop through them
$words = explode(" ", $str);

//i devide each thousands in groups then add them at the end
//For example 2,640,234 "two million six hundred and fourty thousand two hundred and thirty four"
//is defined into 2,000,000 + 640,000 + 234

//the $total will be the variable were we will add up to
$total = 1;

//flag to force the next operation to be an addition
$force_addition = false;

//hold the last digit we added/multiplied
$last_digit = null;

//the final_sum will be the array that will hold every portion "2000000,640000,234" which we will sum at the end to get the result
$final_sum = array();

foreach ($words as $word) {

    //if its not an and or a valid digit we skip this turn
    if (!isset($numbers[$word]) && $word != "and") {
        continue;
    }

    //all small letter to ease the comparaison
    $word = strtolower($word);

    //if it's an and .. and this is the first digit in the group we set the total = 0
    //and force the next operation to be an addition
    if ($word == "and") {
        if ($last_digit === null) {
            $total = 0;
        }
        $force_addition = true;
    } else {
        //if its a digit and the force addition flag is on we sum
        if ($force_addition) {
            $total += $numbers[$word];
            $force_addition = false;
        } else {
            //if the last digit is bigger than the current digit we sum else we multiply
            //example twenty one => 20+1,  twenty hundred 20 * 100
            if ($last_digit !== null && $last_digit > $numbers[$word]) {
                $total += $numbers[$word];
            } else {
                $total *= $numbers[$word];
            }
        }
        $last_digit = $numbers[$word];

        //finally we distinguish a group by the word thousand, million, billion  >= 1000 !
        //we add the current total to the $final_sum array clear it and clear all other flags...
        if ($numbers[$word] >= 1000) {
            $final_sum[] = $total;
            $last_digit = null;
            $force_addition = false;
            $total = 1;
        }
    }



}

// there is your final answer !
$final_sum[] = $total;
print "Final Answer: " . array_sum($final_sum) . "\n";

?>

这篇关于在 php 中将单词转换为数字 II的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 09:34