对字符串中的任何数字使用函数


Use function on any numbers within a string

我试图把它带到这个字符串中

**string** = 55 Banana Slush 25 Test Fifty five Banana Slush twenty five test

现在我有将任何数字转换为单词的功能,这replaceNumtoWord($number)

但是,我需要获取字符串,找到每个数字,然后对字符串中的每个数字使用该函数,而不是从中提取数字。

有什么想法或建议吗?

您可以使用

preg_replace_callback()

$str = preg_replace_callback('/'d+/', function($match) {
    return replaceNumToWord($match[0]);
}, $str);

如果您必须使用不支持匿名函数的旧 PHP 版本:

function _num2word_cb($match) {
    return replaceNumToWord($match[0]);        
}
$str = preg_replace_callback('/'d+/', '_num2word_cb', $str);

旁注:模式'd+将匹配任何数字序列,无论它们出现在哪里,例如,它将匹配"my10, 20, 30foo"中的 10、20 和 30。如果您只想匹配 20,可以将模式更改为 'b'd+'b

您可以使用

preg_replace_callback。

function transNumber($str) {
  return preg_replace_callback('/'d+/', function($matches){
            return replaceNumtoWord($matches[0]);
         }, $str);
}

如果你的 php 版本<5.3,那么你需要定义传递给preg_replace_callback的函数。