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.
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.
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.
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