我在解決這個問題時遇到了一些麻煩。在逗號後面加上空格
我有以下的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
這也保證了空格在逗號後如果失蹤。
它似乎工作,不知道是否有更好的方法。反饋意見:)
謝謝!它的工作原理,但我遇到了另一個問題,請參閱我的編輯 – CyberJunkie 2011-06-06 02:42:11
如果你擺脫檢查逗號,正則表達式將完成你想要的 - preg_replace('/ {2,} /','',$ string ); – jfocht 2011-06-06 03:29:07
啊我看到謝謝。 – CyberJunkie 2011-06-06 15:14:28