Reputation: 5831
I use preg replace to separate numbers by inserting a space between each group of three digits:
$alexa_rank_raw = 8389876;
$alexa_rank = preg_replace("/(\d{3})/", '$1.', $alexa_rank_raw);
// alexa rank becomes: 838.987.6
How can I do the replace so the final number would look like this:
8.389.876
Any ideas?
Upvotes: 1
Views: 3084
Reputation: 437336
You are looking for number_format
.
$rank = number_format($alexa_rank_raw, 0, ",", ".");
But here's also a regex version, because why not?
$rank = preg_replace('/(\d{1,3})(?=(\d{3})+$)/', '$1.', $alexa_rank_raw);
How it works: it matches groups of up to three digits greedily (as many as possible up to three), but uses positive lookahead to assert that there is an exact multiple of three digits starting from the position where the matched group ends all the way up to the end of the input.
Upvotes: 5