2010-11-15 341 views

回答

3

你可以做

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

说明:

(?<=\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 

然后在这个位置插入一个逗号。完成。

这不会插入一个数字和字母(它不会改变21A Broadway21,A Broadway),因为仅\b字母数字和非字母数字字符之间匹配之间的逗号。如果你确实需要这个,请改用/(?<=\d)(?![\d,])/

+0

伟大的答案正则表达式问题 - 很好的正则表达式,解释和替代解决方案。 – alex 2010-11-30 07:15:30

0

你必须要小心你的输入是什么,因为这可能有一些字符串意想不到的结果。

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

编辑回应下面的评论 - 这里是一个版本,如果你的号码不一定跟着空格。结果可能更加出乎意料。

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

大卫从来没有说过数字后面会有空格。 – zzzzBov 2010-11-15 19:36:45

0

这可能会工作,如果数字总是后跟空格。

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

我会分解成两个步骤。首先,删除数字后的所有现有逗号。其次,在所有数字后加逗号。

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

占有欲量词(++)和负前瞻应该做的伎俩:

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

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