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.
My Answer:
You can achieve this by using regular expressions in PHP. Here's a code snippet to extract half-width numbers from a string and separate them into 3 digits:
php
// Original string
$string = "I have 10000 dollars.";
// Extract half-width numbers using regular expression
preg_match_all('/\d+/', $string, $matches);
// Separate each number into 3 digits
foreach ($matches[0] as $match) {
$formatted_number = number_format($match);
$string = str_replace($match, $formatted_number, $string);
}
// Output the converted string
echo $string;
?>
This code snippet will output:
I have 10,000 dollars.
This code uses `preg_match_all` to extract all half-width numbers from the string, then loops through each number and uses `number_format` to separate them into 3 digits. Finally, it replaces the original number with the formatted number in the string.
Rate this post
5 of 5 based on 5037 votesComments