您的问题没有表现出任何努力,但是以下内容可能对您有用:
这在很大程度上取决于您的数字有多长?假设 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