I
I
iDrugov2017-09-19 18:46:09
PHP
iDrugov, 2017-09-19 18:46:09

How to split text into groups of 3 digits with a regular expression?

Actually, the task is to divide any number into groups with a space, for example: 1 234 or 123 456 789, you understand.
The solution, it seems, is obvious: we find three digits at the end and use the looking back, which meets the condition: "if there are digits in front, then put a space." In my mind it was like this:

$var = 123456789;
echo preg_replace('/(?=[0-9])[0-9]{3}$/', '-$0', $var); // пробел заменён на дефис для наглядности
// на выходе: 123456-789

Greedy quantifiers didn't help me, and doing something like ([0-9]){0,3}([0-9]){0,3}([0-9]){0,3} didn't very cool)
Tell me how it is solved.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stimulate, 2017-09-19
@iDrugov

$var = 123456789;
echo number_format($var, 0, ' ', ' ');

L
longclaps, 2017-09-19
@longclaps

Pitonchik, under the puff, somehow distill yourself:

import re
print(re.sub(r'(\b|\d)(\d+?)(?=(?:\d\d\d)+?\b)', r'\1\2.', "1234567890"))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question