How can I explode and trim whitespace? How can I explode and trim whitespace? php php

How can I explode and trim whitespace?


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