0

I have a string of numbers, like so:

$numbers = "one, two, three four, five";

I first explode it by comma:

$numbers_array = explode(",", $numbers);

My result is:

array(4) {
  [0] => string(3)  "one"
  [1] => string(4)  " two"
  [2] => string(11) " three four"
  [3] => string(5)  " five"
}

My question is, how can I achieve this?

array(5) { 
  [0] => string(3) "one" 
  [1] => string(4) "two" 
  [2] => string(6) "three" 
  [3] => string(5) "four" 
  [4] => string(5) "five"
}
id'7238
  • 2,428
  • 1
  • 3
  • 11
zagzter
  • 229
  • 1
  • 11
  • Does this answer your question? [How can I explode and trim whitespace?](https://stackoverflow.com/questions/19347005/how-can-i-explode-and-trim-whitespace) – Melvin Jan 17 '21 at 16:23

2 Answers2

1

This should split your code on spaces and commas:

$numbers = "one, two, three four, five";

$numbers_array = preg_split("/[\s,]+/", $numbers);

You can then remove empty items by doing:

$filtered_numbers_array = array_filter($numbers_array);
Jolan
  • 364
  • 1
  • 10
1
$numbers = "one, two, three four, five,";
$numbers_array = explode(",", $numbers);
$result = [];

foreach($numbers_array as $num){
  $result[] = trim($num);
}

Result:

array (
  0 => 'one',
  1 => 'two',
  2 => 'three four',
  3 => 'five'
)

And this way you can keep your empty item too.