1

An input field on a form accepts a list of comma separated values.

How can I turn those values into an array whether the user enters values with a space after each comma: one, two, three or without one,two,three?

Basically I want to combine $myArray = explode(', ', $myString); and $myArray = explode(',', $myString);

j8d
  • 446
  • 7
  • 23

3 Answers3

8

You have to try the below code:

$myString = "one, two, three";
$myArray = explode(',', $myString);
$trimmed_myArray = array_map('trim',$myArray);
print_r($trimmed_myArray);
Kausha Mehta
  • 2,828
  • 2
  • 20
  • 31
2

As far as I understand, you want trimmed values after exploding. You can use explode & trim & array_map.

$input= 'one, two, three';
$v = explode(',', $input);

$v = array_map('trim', $v);
var_dump($v);

Output

array(3) {
  [0]=>
  string(3) "one"
  [1]=>
  string(3) "two"
  [2]=>
  string(5) "three"
}
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
2

When the value delimiter in your string is variable, preg_split() offers a simple, direct process.

Code: (Demo)

$mystring='one,two,three,four, five, six, seven';
var_export(preg_split('/, ?/',$mystring));

Output:

array (
  0 => 'one',
  1 => 'two',
  2 => 'three',
  3 => 'four',
  4 => 'five',
  5 => 'six',
  6 => 'seven',
)

This is a clean solution because it doesn't require any string preparation or post-split iterative "mopping up". One function call does it all.

The pattern merely explodes on a comma followed by an optional space (the ? means zero or one occurrence of the preceding space).

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • perhaps `/,\s*?/` is a better regex because the provided string may or may not have a space after the commas. – pbarney Jun 11 '21 at 20:12
  • If _your_ situation might also have tabs or newline characters (`\t, `\r`, `\n`), then yes, use `\s`. If _your_ situation might have zero or more whitespace characters (instead of zero or one), then use the `*` quantifier. Modifying the `?` quantifier in this case has no benefit at all. – mickmackusa Jun 11 '21 at 20:41