216

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?

0

11 Answers 11

569

You can do the following using array_map:

$new_arr = array_map('trim', explode(',', $str));
3
  • 12
    This is also looping (internally) by PHP
    – Jason OOO
    Oct 13, 2013 at 15:47
  • 5
    @JasonOOO I think in most people's opinion, a couple milliseconds (if even that) is a fair tradeoff for having a line of code that is short, simple and easily readable.
    – Gavin
    Apr 5, 2017 at 10:52
  • 2
    Simple and easy to understand. However, if dealing with large data sets, the more performant answer provided by @amr-eladwy is the better solution.
    – Yaron
    Mar 10, 2018 at 23:13
72

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"
7
  • 8
    Can anyone explain me why this answer does not have 100 upvotes? Regexp is hard to understand, but it parsed my 100Mb file faster than other solutions
    – Dan
    Aug 18, 2016 at 10:56
  • 2
    Sorry but this regex is wrong - try replacing red with *red*. A better one might be /(\s*,\s*)+/
    – Greg
    Aug 9, 2018 at 7:38
  • @AmrElAdawy FYI this no longer works after the 8/28 update. With the regex in the answer as-is, white space is not trimmed from some of the elements. Ex: ` green thing`.
    – Samsquanch
    Mar 27, 2019 at 15:18
  • 1
    @Samsquanch updated. Please let me know if you see any issue. Mar 27, 2019 at 15:50
  • 1
    Why your regexp not trim spaces around string? Example: ' red, green thing ,, ,, blue ,orange ' Jul 22, 2020 at 12:31
27

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);
2
  • Since array_map and regexp solutions produce identical results, could anyone compare their performance?
    – Dan
    Aug 18, 2016 at 10:42
  • @Dan For cases like this, it will not be any difference.
    – Aris
    Aug 25, 2016 at 5:04
9

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
)
1
  • 2
    this removes space within string. eg., 'navy blue' becomes 'naviblue'
    – manian
    Apr 8, 2022 at 17:46
5

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

3

You can also do this with a one line regex

preg_split('@(?:\s*,\s*|^\s*|\s*$)@', $str, NULL, PREG_SPLIT_NO_EMPTY);
1
  • it creates multiple matches for spaces before and after in a string, for example " one, two, three " generates: Array ( [0] => [1] => one [2] => two [3] => three [4] => [5] => ) Feb 28 at 19:17
1

try this:

$str = preg_replace("/\s*,\s*/", ",", 'red,     green,     blue ,orange');
2
  • The OP wants an array. preg_replace() doesn't generate an array from a string. This is the right answer to the wrong question. Downvoted. Dec 2, 2017 at 9:10
  • 1
    $list = preg_split("/\s*,\s*/", 'red, green, blue ,orange'); minor modification rehabilitates the answer
    – dreftymac
    Aug 3, 2018 at 23:03
1

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

Finally, if you want to split on commas with optional leading or trailing spaces, here is the call: (Demo)

var_export(
    preg_split ('/ *,+ */', $str, 0, PREG_SPLIT_NO_EMPTY)
);
0

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
  )
 */
3
-4
$str = str_replace(" ","", $str);
2
  • 4
    Trim does more than this... It trims \t\n\r\0\x0B also Jun 10, 2014 at 15:59
  • 3
    Not only that, but this will screw up elements with space.
    – Adam Kiss
    Aug 26, 2015 at 19:42
-12

trim and explode

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

$str = trim($str);

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

print_r($strArray);

1
  • 6
    This only strips whitespace from the beginning and end of a string, not between each colour.
    – SeanWM
    Aug 3, 2015 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.