Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add whitespace after comma

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 :)

like image 414
CyberJunkie Avatar asked Dec 01 '22 08:12

CyberJunkie


1 Answers

This worked for me.

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

Explode only at the comma, and all the extra white space is removed. Then implode with a comma space.

like image 63
Richard Testani Avatar answered Dec 04 '22 11:12

Richard Testani