-2

I need to break an array into smaller arrays using a deliminator such as a space, not using a certain numbers of chars (therefore array_chunk will not work for this and these answers How to break an array into a specified number of smaller arrays? is not relevant for the same reason).

Example:

$array1 = ("One two three","four five six","seven eight nine");

Would like to split "One two three" into three elements in one array (using a space as deliminator) and the same for the next two elements. This can be split into multidimensional array as well.

5
  • Post an example of what kind of input you're expecting to get, and what you want the output to be. Commented Sep 16, 2013 at 2:47
  • And why do you think this is best done with regexes? Commented Sep 16, 2013 at 2:49
  • Bec I need to match complex patterns not just a space. Commented Sep 16, 2013 at 2:53
  • What delimiters do you need? Commented Sep 16, 2013 at 2:56
  • EITHER a space or a comma (any two words basically) Commented Sep 16, 2013 at 2:58

1 Answer 1

2
php> $array1 = array("One two three","four five six","seven eight nine");

php> =array_map(function($a){return explode(' ',$a);},$array1)
array(
  0 => array(
    0 => "One",
    1 => "two",
    2 => "three",
  ),
  1 => array(
    0 => "four",
    1 => "five",
    2 => "six",
  ),
  2 => array(
    0 => "seven",
    1 => "eight",
    2 => "nine",
  ),
)

The anonymous function can be changed to however you see fit. Regex, whatever.

edit Per your comments:

php> $array1 = array("One two three","four five,six","seven,eight nine");

php> =array_map(function($a){return preg_split('/[ ,]/',$a);},$array1)
array(
  0 => array(
    0 => "One",
    1 => "two",
    2 => "three",
  ),
  1 => array(
    0 => "four",
    1 => "five",
    2 => "six",
  ),
  2 => array(
    0 => "seven",
    1 => "eight",
    2 => "nine",
  ),
)
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, the OP is asking what function can do regex split, for which preg_split should be the answer. au1.php.net/preg_split
I don't see that in the Q
^^ No, you did not understand the question (justhalf)
a space or a comma is not actually a complex pattern, haha

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.