How can I explode and trim whitespace?
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"
You can do the following using array_map:
$new_arr = array_map('trim', explode(',', $str));