我有这个示例字符串:hello77boss2america-9-22-fr99ee-9
。应在字符串的所有个位数前面添加前导 0。结果应该是:hello77boss02america-09-22-fr99ee-09
我尝试了下面的代码:
str_replace("(0-9)","0",$num);
您可以使用预替换 http://php.net/manual/en/function.preg-replace.php找到单独的数字并替换它们,就像......
<?php
echo preg_replace(
'~(?<!\d)(\d)(?!\d)~',
'0$1',
'hello77boss2america-9-22-fr99ee-9'
); //hello77boss02america-09-22-fr99ee-09
这是一个更具描述性的版本。
<?php
$callback = function($digit) {
$digit = $digit[0];
if (1 == strlen($digit)) {
$digit = "0$digit";
}
return $digit;
};
echo preg_replace_callback('~\d+~', $callback, 'hello77boss2america-9-22-fr99ee-9');
// hello77boss02america-09-22-fr99ee-09
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)