开发者

Php format numbers in a string with regexp

开发者 https://www.devze.com 2023-01-19 06:22 出处:网络
I need help with writing a regular expression in PHP. I am not friend enough to get it right. I need to find all integers in a string and format them as follows:

I need help with writing a regular expression in PHP. I am not friend enough to get it right. I need to find all integers in a string and format them as follows:

1 to 001000
0.13 to 000130
100 to 0100000 

and so on. In normal speech it means - edit the number prepend it with zeros or edit it to be in same "order". The point is to have all of the integers it the string in this format (6 numbers). Could someone开发者_C百科 help me please? I will not post my tryouts here because they are too foolish:-)


From your examples looks like you are multiplying the number with 1000 and prefixing them with 0's to make a total of 6 digits. If that is true you can just do:

sprintf("%06d",$n*1000);


By using the 'e' modifier on preg_replace() (or using preg_replace_callback()) you can use @codaddict's answer:

function my_format($d) {
    return sprintf('%06d', round($d * 1000));
}

$your_string = '0.12 100 number 1.12 something';

preg_replace('/\d+(\.\d+)?/e', 'my_format(\\0)', $your_string);
// Should give '000120 100000 number 001120 something'
0

精彩评论

暂无评论...
验证码 换一张
取 消