简体   繁体   English

PHP preg_replace数字位数

[英]PHP preg_replace number of digits

i have this: 我有这个:

preg_replace('/(\d{1}|\d{2})/gi', '$1', 'some number');

If text is one digit number $1 returns one digit number, if it is 2 digit it return 2 digit number...., but I need to returned number was always been 2 digit: 如果文本是一位数字,则$ 1返回一位数字,如果是2位,则返回2位数字....,但是我需要返回的数字始终是2位:

1 => 01 
2 => 02
...
10 => 10
...
99 => 99

How can I do that? 我怎样才能做到这一点?

Use str_pad(). 使用str_pad()。 It's a lot cheaper. 便宜很多。 http://php.net/str_pad http://php.net/str_pad

why so complex? 为什么这么复杂? KISS and use str_pad 并使用str_pad

echo str_pad($input, 2, "0", STR_PAD_LEFT);

您的意思是这样吗?使用e修饰符,使用preg_replace函数执行php代码,以及满足您要求的任何str_padsprintf

preg_replace('/(\\d{1}|\\d{2})/ie', 'sprintf("%02d",$1)', 'some number');

Please use str_pad() . 请使用str_pad() The e modifier is DEPRECATED as of PHP 5.5.0 and should be avoided. 从PHP 5.5.0开始, e修饰符已弃用,应避免使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM