简体   繁体   中英

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 => 01 
2 => 02
...
10 => 10
...
99 => 99

How can I do that?

Use str_pad(). It's a lot cheaper. http://php.net/str_pad

why so complex? KISS and use 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() . The e modifier is DEPRECATED as of PHP 5.5.0 and should be avoided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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