How can I explode and trim whitespace?

For example, I would like to create an array from the elements in this string:

$str = 'red,     green,     blue ,orange';

I know you can explode and loop through them and trim:

$arr = explode(',', $str);
foreach ($arr as $value) {
    $new_arr[] = trim($value);
}

But I feel like there's a one line approach that can handle this. Any ideas?


You can do the following using array_map:

$new_arr = array_map('trim', explode(',', $str));

An improved answer

preg_split ('/(\s*,*\s*)*,+(\s*,*\s*)*/', 'red,     green thing ,,
              ,,   blue ,orange');

Result:

Array
(
    [0] => red
    [1] => green thing
    [2] => blue
    [3] => orange
)

This:

  • Splits on commas only
  • Trims white spaces from each item.
  • Ignores empty items
  • Does not split an item with internal spaces like "green thing"

The following also takes care of white-spaces at start/end of the input string:

$new_arr = preg_split('/\s*,\s*/', trim($str));

and this is a minimal test with white-spaces in every sensible position:

$str = ' first , second , third , fourth, fifth ';
$new_arr = preg_split('/\s*,\s*/', trim($str));
var_export($str);