我有以下示例字符串:hello77boss2america-9-22-fr99ee-9
。应在字符串的所有一位数字前添加前导0。结果应为:hello77boss02america-09-22-fr99ee-09
我尝试了下面的代码:
str_replace("(0-9)","0",$num);
您可以使用preg_replace查找并替换孤立的数字,例如...
<?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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句