Comma delimited strings match and separately with regex (find and replace / preg_replace)

I have a list:

cat, dog, duck

I want to get the words from this list and store them separately. so:

cat dog duck

I tried this regex but it doesn't work properly for me: ([^,]+) https://www.regextester.com/108606

The problem is that I don't get the words, I just get the commas, this: ,,

It would be needed for software that works in a php-based preg_replace way. Here's how I used it:

Find: ([^,]+)

Replace: leave empty

Can you help me with the right regex that gets the words separately from the comma-separated list and stores them separately? I searched the internet (I didn’t get it) but couldn’t find a solution.

Upvotes: 0

Views: 55

Answers (1)

ezio4df
ezio4df

Reputation: 4185

Try something like this,

1:

$str = 'cat, dog, duck';
$splitted = preg_split('~(,\s*)~', $str);

var_export($splitted);

Checkout: preg-split()

2:

$str = 'cat, dog, duck';

$split = explode(',', $str);
$split = array_map( // Removes Starting Whitespace
    function($v) {
        return ltrim($v);
    }, $split); 

var_export($split);

Checkout: explode(), array_map(),

All of them also removes the spaces after ,. So, You get exact output as desired.

Output,

array (
  0 => 'cat',
  1 => 'dog',
  2 => 'duck',
)

Upvotes: 0

Related Questions