Php format numbers in a string with regexp

后端 未结 2 867
情话喂你
情话喂你 2021-01-21 18:25

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:



        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-21 18:55

    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'
    

提交回复
热议问题