在 php 中将单词转换为数字 II

2024-05-14

这里有一个很棒的功能在 PHP 中将单词转换为数字 https://stackoverflow.com/questions/1077600/converting-words-to-numbers-in-php来自埃尔约博。 但我有一个问题,字符串必须以书面数字开头。 如何转换例如“iPhone 有二十三万、七百八十三个应用程序”?

解释的功能:

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/ 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";

?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 php 中将单词转换为数字 II 的相关文章

  • php 错误地将字符串中的 ¬ 转换为 Ø

    我需要在 PHP 中组成一个简单的字符串 它是要发布到另一个站点的数据字符串 问题是其中一个字段是 notify url 当我使用该字段时 PHP 将其前面的 和 not 部分表示逻辑运算符 AND NOT 并将其转换为 字符 string
  • PHP:会话.auto_start

    我在同一台服务器上有两个项目 它们的设置在 session auto start 中冲突 相关post https stackoverflow com questions 1378324 php setting variables in i
  • Symfony2 - 多种形式的主题

    有没有办法在同一页面上的两个 或多个 表单使用不同的主题 我有 2 个表单 我想对第一个表单使用主题 X 对第二个表单使用主题 Y 您需要在显示表单之前声明您的主题 你应该试试 form theme form ThemeX html twi
  • PHP 中的致命错误是什么意思?

    我收到以下错误 致命错误 未捕获错误 调用未定义的函数 var dumb 这是什么意思 致命错误是什么意思 这是一个导致脚本中止并立即退出的错误 致命错误之后的所有语句都不会被执行
  • Woocommerce 从 woocommerce_add_to_cart_fragments 传回的错误片段

    我正在创建自定义 WooCommerce 购物车 并且更新购物车商品的数量工作正常 唯一的问题是它不会自动刷新 只有在页面加载后才起作用 我当前的代码使用woocommerce add to cart fragments挂钩并使用传入的 f
  • 查找所有具有相同值的数组键

    当值未知时 是否有一种更简单的方法来获取具有相同值的所有数组键 The problem with array unique是它返回唯一的数组 因此它找不到唯一的值 例如 从这个数组 Array a gt 1000 b gt 1 c gt 1
  • 我可以解密通过 PHP 加密的 C++ 数据吗?

    我正在使用 mcrypt encrypt 和 base64 encode 来加密 php 中的数据 我尝试用C 解密数据 但没有成功 我有使用多年的 C Rijndael 逻辑 以及 base64 decode 逻辑 后者完美地解码了 ph
  • 终端从包含空格的变量传递参数

    在终端中如何将包含空格的字符串作为参数传递 它实际上跳过了空格后面的部分 只取第一个单词 word soccer ball shell exec casperjs test js word word 那么我怎样才能转义空白它只运行这个命令
  • 使用命名占位符时 PHP/SQL 插入错误

    我有以下 PHP PDO 语句 STH this gt db gt prepare INSERT INTO UserDetails FirstName LastName Address City County PostCode Phone
  • Wordpress 编辑器中的“application/gas-events-abn”对象是什么?

    我正在使用 Wordpress 创建博客 我注意到当我多次保存帖子时 代码中会出现一个奇怪的元素 在帖子底部创建一个大的空白区域 代码如下所示 post content nbsp 每次我编辑帖子时 我都必须将其删除 Joomla 有时也会发
  • 以编程方式添加数字签名外观?

    我正在以编程方式对我的 PDF 文件进行签名 并且我想将签名外观添加到 PDF 我需要哪些对象才能实现此目的 我知道我必须Annotations BBox and XObject但我真的不知道按什么顺序以及是否需要其他东西 调试此类内容以找
  • PHP/MySQL - 在数据库中存储数组

    我正在开发一个 PHP 应用程序 它需要将各种设置存储在数据库中 客户经常询问是否可以添加或更改 删除某些内容 这导致了表格设计出现问题 基本上 我有很多布尔字段 它们只是指示是否为特定记录启用了各种设置 为了避免再弄乱表格 我正在考虑将数
  • 字符串不等于其自身

    But why if i echo good else echo bad echos gt gt bad 您应该复制此片段 如果你手写的话 它会起作用 它让我疯狂 你太狡猾了 第二个 I 不是小写拉丁文小写 i 我把它转储了 hexdump
  • Codeigniter,为MySQL创建表和用户

    我想以编程方式使用 CI 创建数据库和用户 到目前为止 我有这 2 个简单的 MySQL 语句 CREATE DATABASE testdb DEFAULT CHARACTER SET utf8 COLLATE utf8 general c
  • php-curl 不支持 url 中的 utf-8

    我正在尝试将 http 请求从我的服务器发送到 php 中的另一台服务器 例如 我发送请求的 URL 包含一些 utf8 字符http www aparat com etc api videoBySearch text http www a
  • 如何将 javascript 倒计时器与服务器同步

    我有一个拍卖网站 有一个 JavaScript 计时器倒计时 由于某种原因 15 20 分钟后 该计时器比实际时间滞后 20 30 秒 在 1 小时的过程中 JavaScript 倒计时器可能会关闭至少 2 3 分钟 这让用户感到困惑 因为
  • MongoDB 给出奇怪的连接错误

    我在使用 PHP 连接 MongoDB 时遇到问题 这是我的代码 这会产生以下错误 Fatal error Uncaught exception MongoConnectionException with message localhost
  • DOMDocument 对我的字符串做了什么?

    dom new DOMDocument 1 0 UTF 8 str p Hello p var dump mb detect encoding str dom gt loadHTML str var dump dom gt saveHTML
  • ruby 中可以做动态变量吗? [复制]

    这个问题在这里已经有答案了 我可以通过其他方式实现这种动态性质 但这引起了我的好奇 Ruby 中有类似的机制吗 varname hello varname world echo hello Output world 您可以使用以下方法实现类
  • LDAP 过滤器用于区分名称

    我使用以下代码成功查询 Active Directory 中的用户 filter objectCategory person samaccountname someusername fields array samaccountname m

随机推荐

  • C# 中的浮动花括号

    今天我遇到了一段以前从未见过的 C 代码 程序员仅使用花括号定义了代码块 没有 if 类 函数等 int i 0 i compile error 除了让代码看起来更有条理之外 这样做还有其他目的吗 使用这种 浮动 上下文是好还是坏 您可以使
  • 如何使用 .gitattributes 避免在 git root 中包含文件夹,但在 zip 的 dist 文件夹中包含同名文件夹

    我有一个名为lib在存储库的根目录和另一个名为lib在 dist 文件夹中 我正在尝试使用 gitattributes文件排除除 dist 之外的所有文件夹和文件 以便任何下载为 zip 或 tarball 的人都只会 git 分发文件 我
  • Android:如何暂停和恢复可运行线程?

    我正在使用 postDelayed 可运行线程 当我按下按钮时 我需要暂停并恢复该线程 请任何人帮助我 这是我的主题 protected void animation music6 music4 postDelayed new Runnab
  • Object.entries() 确实为 Maps 返回一个空数组

    我刚刚发现 那个呼唤Object entries在 Map 上确实返回一个空数组 我希望它返回任何返回的内容Map entries Example let map new Map 1 2 map entries 1 2 Object ent
  • 如何在 Visual C++ 中宣传 Bonjour 服务

    我试图弄清楚这是否可能 但是通过 Visual C 宣传 Bonjour 服务的最简单方法是什么 您可以使用DNS服务发现客户 dns sd Windows Bonjour 安装程序把它放进去C Windows system32 dns s
  • 我可以在 dojo 手风琴中打开特定条目吗?

    我想在应用程序的左侧导航中放置链接 打开 xPage 并选择特定的手风琴条目 不知道该怎么做 有什么想法吗 我在这里假设您想以编程方式执行此操作 看看这个答案 https stackoverflow com a 1190455 104799
  • Laravel 转义 Blade 模板中的所有 HTML

    我正在 Laravel 中构建一个小型 CMS 并尝试显示内容 存储在数据库中 它显示 HTML 标签而不是执行它们 就像所有打印数据都有一个自动 html entity decode 一样
  • Cleancode:在 Promise 中尝试/捕获

    我正在研究 redux form atm 并找到了这段代码 它对我有用 但是有没有更干净的方法可以用 ES6 风格编写它 const asyncValidate values dispatch gt return new Promise r
  • 有效地生成所有排列

    我需要尽快生成所有排列 https en wikipedia org wiki Permutation整数的0 1 2 n 1并得到结果作为NumPy https numpy org 形状数组 factorial n n 或者迭代此类数组的
  • vscode通过SSH连接gitlab的问题

    我在尝试通过 SSH 连接到 GitLab 远程存储库时遇到问题 这里是迄今为止完成的步骤 成功生成 SSH 密钥 管理人员将密钥添加到存储库中 因此当我访问 GitLab 网站时 我可以提交和发布分支 我无法从 VSCODE 发布分支并收
  • iPad Safari 100% 高度问题

    我的页面上有一个模态 div 它使背景变灰 如果我将overlay div的高度设置为100 它在IE 桌面 上工作正常 但在iPad Safari上 完整的高度不会变灰 究竟是什么问题 这与固定位置 视口有关吗 请帮忙 下面是相同的 CS
  • 将 Python 中的 SHA 哈希计算转换为 C#

    有人可以帮我将以下两行 python 代码转换为 C 代码吗 hash hmac new secret data digestmod hashlib sha1 key hash hexdigest 8 如果您有兴趣 其余的看起来像这样 us
  • 需要使用 imap php 保存电子邮件副本,然后可以在 Outlook Express 中打开

    我有 IMAP PHP 脚本 它连接并读取邮箱中的电子邮件 我正在寻找的是 我想将电子邮件保存在服务器磁盘上 并将其命名为 testing eml 文件 因此 当我稍后记下这些电子邮件时 可以在 Outlook Express 中查看 任何
  • 如何在 PHP 中使用 RS256 签署 X.509 证书?无法获取有效指纹...x5t

    我已经实现了 JWT 令牌生成器库Here https github com F21 jwt blob master JWT JWT php 并且我能够获得 RS256 令牌 有效负载 但我对标题数据有疑问 我需要一个标头值 x5t 该标头
  • 在 Magento 中获取购物车详细信息

    我想通过使用 Magento 获取购物车详细信息getQuote功能 我怎样才能做到这一点 cart Mage getModel checkout cart gt getQuote 当我打印 cart页面停止执行并显示空白页面 但是当我写的
  • Azure 网站中的 404 处理

    我在 Azure 上有一个 MVC 网站 我已经编写了一个控制器操作来代表资源 该操作应该返回 HTTP 404 但正文内容应该是一些 HTML 我在其中解释了 404 的原因 这是作为一个标准操作实现的 该操作设置Response Sta
  • 如何在 Safari 上打开本地 html 文件?

    我想打开本地 html 文件Safari集成到我的Swift 3应用 我知道如何使用网址来做到这一点 这是我用来执行此操作的代码 let encodedString url addingPercentEncoding withAllowed
  • Docx 缺少属性

    我正在尝试使用 python 中的 docx 库来考虑 word 文档 问题是 无论我导入什么 我都会收到有关 无属性 的错误消息 例如 文档 from docx import Document 给出输出 cannot import nam
  • 如何使用 solrnet 在 solr 中使字段搜索不区分大小写

    在 solr 模式中我有如下字段
  • 在 php 中将单词转换为数字 II

    这里有一个很棒的功能在 PHP 中将单词转换为数字 https stackoverflow com questions 1077600 converting words to numbers in php来自埃尔约博 但我有一个问题 字符串