I’m having some trouble figuring this out.
I have the following CSV string
hello world, hello world, hello
The middle value has excess whitespaces. I’m trimming that using
preg_replace('/( )+/', ' ', $string)
The function is excellent but it removes the whitespaces after the commas as well. It becomes..
hello world,hello world,hello
I want to preserve 1 whitespace after commas like so
hello world, hello world, hello
How can I do this?
EDIT:
Using preg_replace('/(?<!,) {2,}/', ' ', $string); as suggested, works but I ran into another issue.. When I use more than 1 whitespace after a comma it return 2 whitespaces after the comma.
so
hello world, hello world,hello
returns
hello world, hello world, hello
As a solution I create an array from the CSV string and used 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
Now I get hello world, hello world, hello It also ensures a whitespace after comma if missing.
It seems to work, not sure if there is better way. Feedbacks are welcomed 🙂
This will match 2 or more spaces together and replace with a singular space. It won’t match a space after a comma.
RegExr