开发者

Regex to add a comma after every sequence of digits in a string

I want a regex or something to loop on all numbers in a string and add a comma after them. but if there is already a com开发者_运维知识库ma then it shouldn't do it.

Example:

$string="21 Beverly hills 90010, CA";

Output:

$string="21, beverly hills 90010, CA";

Thanks


You could do

$string = preg_replace('/(?<=\d\b)(?!,)/', ',', $string);

Explanation:

(?<=\d\b) # Assert that the current position is to the right of a digit
          # and that this digit is the last one in a number 
          # (\b = word boundary anchor).
(?!,)     # Assert that there is no comma to the right of the current position

Then just insert a comma in this position. Done.

This will not insert a comma between a number and a letter (it will not change 21A Broadway into 21,A Broadway) because \b only matches between alphanumeric and non-alphanumeric characters. If you do want this, use /(?<=\d)(?![\d,])/ instead.


You'd have to be careful about what your input was, since this could have unexpected results with some strings.

preg_replace('/([0-9])(\s)/', '$1,$2', $string);

EDIT in response to the comment below -- here's a version if your numbers are not necessarily followed by spaces. Results could be even more unexpected.

preg_replace('/([0-9])([^,0-9])/', '$1,$2', '21 Beverly hills 90010, CA');


Possessive quantifier (++) and negative lookahead should do the trick:

$string="21 Beverly hills 90010, CA";

echo preg_replace('/\d++(?!,)/', '$0,', $string);


This would probably work if the numbers are always followed by spaces.

$string = preg_replace('/(\d+)(\s)/', '$1,$2', $string);


I would break this into two steps. First, remove all existing commas after numbers. Second, add commas after all numbers.

$string = preg_replace('/([0-9]+),/', '$1', $string);
$string = preg_replace('/([0-9]+)/', '$1,', $string);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜