2012-08-26 73 views
0

以簡單的方式使用php regexp,是否可以修改字符串以便在逗號或句點之後添加一個空格,後面跟有單詞,但不能在逗號或句點後面加上數字,例如1,000.00?regexp在逗號之後添加空格,但逗號爲千位分隔符時不會添加空格?

String,looks like this with an amount of 1,000.00 

需要改變,以...

String, looks like this with an amount of 1,000.00 

這樣做可以使課程的多個實例......這是我現在使用的是什麼,但它造成的數字返回爲1, 000 00

$punctuation = ',.;:'; 
$string = preg_replace('/(['.$punctuation.'])[\s]*/', '\1 ', $string); 

回答

0

您可以用', '取代'/(?<!\d),|,(?!\d{3})/'

喜歡的東西:

$str = preg_replace('/(?<!\d),|,(?!\d{3})/', ', ', $str); 
+0

這是真正接近我正在尋找...你將如何修改這與我提供的代碼示例中的$標點符號變量一起工作?謝謝 –

+0

'$ str = preg_replace('/(?<!\ d)['。$標點符號。'] | ['。$標點符號。'](?!\ d {3})/','$ 0', $ STR);' – Barmar

0

我正在尋找此正則表達式。

這篇文章對我真的很有幫助,我改進了Qtax提出的解決方案。

這裏是我的:

$ponctuations = array(','=>', ','\.'=>'. ',';'=>'; ',':'=>': '); 
foreach($ponctuations as $ponctuation => $replace){ 
    $string = preg_replace('/(?<!\d)'.$ponctuation.'(?!\s)|'.$ponctuation.'(?!(\d|\s))/', $replace, $string); 
} 

通過這一解決方案, 「一句話:這個」 不會被改爲 「一句話:   本」(蒙山2個布蘭克空格)

這一切。

相關問題