2011-06-06 108 views
2

我在解決這個問題時遇到了一些麻煩。在逗號後面加上空格

我有以下的CSV字符串

hello world, hello    world, hello 

中間值有多餘的空格。我正在修剪,使用

preg_replace('/()+/', ' ', $string) 

該功能是優秀的,但它也刪除逗號後面的空格。它成爲..

hello world,hello world,hello

我想逗號後保留1個空白像這樣

hello world, hello world, hello

我怎樣才能做到這一點?

編輯:

使用preg_replace('/(?<!,) {2,}/', ' ', $string);的建議,工作,但我遇到了另一個問題。當我使用超過1個空白逗號後的逗號後返回2個空格。

所以

hello world,    hello world,hello 

回報

hello world, hello world, hello 

當我創建了CSV字符串數組的解決方案,並用於implode()

$string = "hello world, hello  world,hello"; 
$val = preg_replace('/()+/', ' ', $string); 
$val_arr = str_getcsv($val); //create array 
$result = implode(', ', $val_arr); //add comma and space between array elements 
return $result; // Return the value 

現在,我得到hello world, hello world, hello這也保證了空格在逗號後如果失蹤。

它似乎工作,不知道是否有更好的方法。反饋意見:)

回答

6

這將匹配2個或更多的空間在一起,並用一個單一的空間替換。逗號後面的空格不匹配。

preg_replace('/(?<!,) {2,}/', ' ', $string); 

RegExr

+0

謝謝!它的工作原理,但我遇到了另一個問題,請參閱我的編輯 – CyberJunkie 2011-06-06 02:42:11

+1

如果你擺脫檢查逗號,正則表達式將完成你想要的 - preg_replace('/ {2,} /','',$ string ); – jfocht 2011-06-06 03:29:07

+0

啊我看到謝謝。 – CyberJunkie 2011-06-06 15:14:28

2

,而不是使用+量詞,它匹配1個或多個空格,請使用{2}量詞,這將只匹配2個或多個空格... 「你好」 韓元不符合。

+0

謝謝!它的工作原理,但我遇到了另一個問題,請參閱我的編輯 – CyberJunkie 2011-06-06 02:42:19

+0

@Cyber​​Junkie:這不是這裏的建議。這裏的建議是簡單地使用'/ {2,} /'(不含'(? trutheality 2011-06-06 06:02:08

+0

對不起,我用正則表達式很新 – CyberJunkie 2011-06-06 15:14:48

8

這對我有效。

$string = "hello world, hello  world,hello"; 
$parts = explode(",", $string); 
$result = implode(', ', $parts); 
echo $result; // Return the value 
//returns hello world, hello world, hello 

只能用逗號分解,所有額外的空白都會被刪除。 然後用逗號分隔空間。