【问题标题】:PHP - How to change numbers in a string to letters [closed]PHP - 如何将字符串中的数字更改为字母[关闭]
【发布时间】:2015-04-15 23:59:59
【问题描述】:

我有这样的字符串:

$string = "2 blocks and 4 allerts";

我想把数字2和4转换成字母,输出如下:

$output = "two blocks and four allerts;

我曾尝试使用 str_replace() 函数,但它只在字符串有一个数字时才有效。

function ( $string = "2 blocks and 4 allerts" ) { 
    return str_replace( 2, 'two', $string );
}

【问题讨论】:

标签: php


【解决方案1】:

您的问题没有表现出任何努力,但是以下内容可能对您有用:

这在很大程度上取决于您的数字有多长?假设 0 到 9,你会这样做:

$numbers = array(0,1,2,3,4,5,6,7,8,9);

$number_words = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');

$string = "I have 3 apples.";

$new_string = str_replace($numbers, $number_words, $string);

上述解决方案适用于简单的单词和替换。

例如,对于像 1995445 这样的数字,您应该在互联网上搜索一个(或写一个)将数字转换为字符串的函数。

这是一个很好的功能: http://www.karlrixon.co.uk/writing/convert-numbers-to-words-with-php/

我们要做的,是首先从字符串中提取数字:

$rule = "/([0-9]+)/";
$string = "I have 2 mobile phones, each containing 2500 messages";
$num_match;

然后我们遍历字符串。每次我们只替换第一个出现的数字时,捕获它,将它传递给我们的number_to_string() 函数,然后获取字符串,在我们的替换函数中使用返回的字符串,即 preg_replace()。我们利用preg_replace()$limit 参数将替换限制在每次迭代的第一次出现:

while( preg_match($rule, $string, $num_match) )
{
    $string = preg_replace("/".$num_match[0]."/", number_to_string($num_match[0]), $string, 1);
}

echo $string;

然后我在浏览器中得到的是:

I have two mobile phones, each containing two thousands and five hundred messages

【讨论】:

  • 哇,谢谢。答案足以帮助我理解我的错误。再次感谢您。
  • 很高兴看到它对您有用。
猜你喜欢
  • 2021-10-28
  • 2018-02-12
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
  • 2013-09-15
相关资源
最近更新 更多