如何使用正则表达式和PHP格式化数字[关闭]

I am practicing for regular expressions.

I was trying to format numbers using PHP and regex. I want to add comma after each 3 digits like this 111222333444 to this format 111,222,333,444 or 11222333444 to 11,222,333,444 by using PHP and Regular expression.

I searched a lot but I could not find exact solution for this.

I know that there is function in php (number_format) to do this but I want to use Regular expression and PHP to do this because I am learning regex and practicing so I want to use regex and php only.

Here is a regex based solution:

$repl = preg_replace('/(?!^)(?=(?:\d{3})+$)/m', ',', $input);

RegEx Demo

Explanation:

  • (?!^) - Negative lookahead to make sure we are not at start of input
  • (?=(?:\d{3})+$) - Positive lookahead to make sure there 1 or more of 3 digit sets following current position
  • Replacement is just a literal comma
  • More explanation is available at linked demo