How can I explode and trim whitespace?

PhpExplodeTrimHigher Order-Functions

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

You can do the following using array_map:

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

Solution 2 - Php

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"

Solution 3 - Php

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

Solution 4 - Php

this how you replace and explode in a single line of code

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

$new_string = explode(',',preg_replace('/\s+/', '', $str));

will output the results as

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

Solution 5 - Php

By combining some of the principals in the existing answers I came up with

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

The reasoning behind it is that I found a bug in this answer, where if there is a comma at the end of the string it'll return a blank element in the array. i.e.

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

Results in

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

You can fix this by using PREG_SPLIT_NO_EMPTY as mentioned in this answer to remove it, but once you are doing that there is technically no need to remove consecutive commas via the regex, thus the shortened expression

Solution 6 - Php

You can also do this with a one line regex

preg_split('@(?:\s*,\s*|^\s*|\s*$)@', $str, NULL, PREG_SPLIT_NO_EMPTY);

Solution 7 - Php

try this:

$str = preg_replace("/\s*,\s*/", ",", 'red,     green,     blue ,orange');

Solution 8 - Php

SPECIFICALLY for the OP's sample string, because each substring to be matched is a single word, you can use str_word_count().

Code: (Demo)

$str = ' red,     green,     blue ,orange ';
var_export(str_word_count($str,1));  // 1 means return all words in an indexed array

Output:

array (
  0 => 'red',
  1 => 'green',
  2 => 'blue',
  3 => 'orange',
)

This can also be adapted for substrings beyond letters (and some hyphens and apostrophes -- if you read the fine print) by adding the necessary characters to the character mask / 3rd parameter.

Code: (Demo)

$str = " , Number1 ,     234,     0 ,4heaven's-sake  ,  ";
var_export(str_word_count($str,1,'0..9'));

Output:

array (
  0 => 'Number1',
  1 => '234',
  2 => '0',
  3 => '4heaven\'s-sake',
)

Again, I am treating this question very narrowly because of the sample string, but this will provide the same desired output:

Code: (Demo)

$str = ' red,     green,     blue ,orange ';
var_export(preg_match_all('/[^, ]+/',$str,$out)?$out[0]:'fail');

Solution 9 - Php

You can use preg_split() for that.

$bar = preg_split ('/[,\s]+/', $str);
print_r ($bar);

/* Result:
  Array
  (
      [0] => red
      [1] => green
      [2] => blue
      [3] => orange
  )
 */

Solution 10 - Php

$str = str_replace(" ","", $str);

Solution 11 - Php

> trim and explode

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

$str = trim($str);

$strArray = explode(',',$str);

print_r($strArray);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSeanWMView Question on Stackoverflow
Solution 1 - PhpSeanWMView Answer on Stackoverflow
Solution 2 - PhpAmr ElAdawyView Answer on Stackoverflow
Solution 3 - PhpDiego PeriniView Answer on Stackoverflow
Solution 4 - PhpAmit SharmaView Answer on Stackoverflow
Solution 5 - PhpshmurfView Answer on Stackoverflow
Solution 6 - PhpDomView Answer on Stackoverflow
Solution 7 - PhpJason OOOView Answer on Stackoverflow
Solution 8 - PhpmickmackusaView Answer on Stackoverflow
Solution 9 - PhpSutandionoView Answer on Stackoverflow
Solution 10 - PhpBlackWhiteView Answer on Stackoverflow
Solution 11 - PhpAnil M SainiView Answer on Stackoverflow