php - Regex to add a comma after every sequence of digits in a string -
i want regex or loop on numbers in string , add comma after them. if there comma shouldn't it.
example:
$string="21 beverly hills 90010, ca";
output:
$string="21, beverly hills 90010, ca";
thanks
you do
$string = preg_replace('/(?<=\d\b)(?!,)/', ',', $string);
explanation:
(?<=\d\b) # assert current position right of digit # , digit last 1 in number # (\b = word boundary anchor). (?!,) # assert there no comma right of current position
then insert comma in position. done.
this not insert comma between number , letter (it not change 21a broadway
21,a broadway
) because \b
matches between alphanumeric , non-alphanumeric characters. if want this, use /(?<=\d)(?![\d,])/
instead.
Comments
Post a Comment