在逗号后添加空白


Add whitespace after comma

我想不通。

我有以下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。如果缺少逗号,它还确保逗号后面有空白。

它似乎有效,不确定是否有更好的方法。欢迎反馈:)

这对我有效。

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

仅在逗号处分解,所有多余的空白都将被删除。然后用逗号空格内爆。

这将把2个或多个空间匹配在一起,并替换为奇异空间。它与逗号后面的空格不匹配。

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

RegExr

不要使用匹配1个或多个空格的+限定符,而是使用只匹配2个或更多空格的{2,}限定符。。。",你好"与此不匹配。