Reputation: 327
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
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
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