zagzter
zagzter

Reputation: 327

Explode String by Comma and again with space

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"
}

Upvotes: 0

Views: 787

Answers (2)

Vicol Cristian
Vicol Cristian

Reputation: 105

$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.

Upvotes: 1

Jolan
Jolan

Reputation: 364

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

Upvotes: 1

Related Questions