-1

How can I extract half-width numbers in a character string and separate them into 3 digits with php?

Example  original string:I have 10000 dollars.  After conversion:I have 10,000 dollars.

supermonkey
  • 631
  • 11
  • 25
  • Please show us your best attempt (code), you might be closer than you think. What does not work as expected? Please read [ask] and take the [tour]! – berend Jun 16 '21 at 18:14

1 Answers1

0

I am probably missing something with regards to the half-width number, but this seems to work:

<?php

$before = 'I have 10000 dollars.';
$expect = 'I have 10,000 dollars.';

$result = preg_replace_callback(
    '/\d+/',
    function($number) { 
        return number_format($number[0]); 
    },
    $before
);

var_dump($result === $expect);
echo $result; // I have 10,000 dollars.

Demo https://3v4l.org/oK7bk

If you need control over the number format, check my other answer on this here: How to format an int in format U.S. in European format

Gordon
  • 312,688
  • 75
  • 539
  • 559