PHP:如何在preg_replace中传参给NumberToWords替换字符串数字为单词
解决方案
要实现将字符串中的数字替换为对应的英文单词,你需要使用preg_replace_callback而非普通的preg_replace——后者无法将匹配到的动态内容传入目标函数。
代码示例
假设你已定义好NumberToWords函数,以下是完整的实现代码:
// 你已有的数字转英文单词函数 function NumberToWords($num) { // 这里替换为你实际的转换逻辑,以下是简单示例 $numberMap = [ '3' => 'three', '5' => 'five', // 可扩展更多数字映射 ]; return isset($numberMap[$num]) ? $numberMap[$num] : $num; } $str = "There are 3 cats and 5 dogs"; // 使用preg_replace_callback处理替换 $convertedStr = preg_replace_callback( '/[0-9]/', // 匹配单个数字的正则 function($matches) { // $matches[0]是当前匹配到的数字字符串 return NumberToWords($matches[0]); }, $str ); echo $convertedStr; // 输出:There are three cats and five dogs
关键说明
为什么不用preg_replace?
当你直接写preg_replace("/[0-9]/", NumberToWords(), $str)时,NumberToWords()会在执行preg_replace前先被调用(此时没有传入任何匹配的数字),导致替换逻辑完全失效。处理多位数的扩展
如果你的字符串中存在多位数(比如12),只需将正则表达式修改为/\d+/,即可匹配完整的数字序列,再传入NumberToWords处理多位数转换。
内容的提问来源于stack exchange,提问作者lStoilov
相关产品推荐
相关产品推荐

