0

This question is different to Split, a string, at every nth position, with PHP, in that I want to split a string like the following:

foo|foo|foo|foo|foo|foo

Into this (every 2nd |):

array (3) {
  0 => 'foo|foo',
  1 => 'foo|foo',
  2 => 'foo|foo'
}

So, basically, I want a function similar to explode() (I really doubt that what I'm asking will be built-in), but which 'explodes' at every nth appearance of a certain string.

How is this possible?

2
  • 1
    Why completely change your question via an edit rather than asking a new one? Commented Oct 6, 2012 at 9:53
  • @JonLin I've ran out of space to ask questions, and I'm urgent. Commented Oct 6, 2012 at 10:16

1 Answer 1

2

You can use explode + array_chunk + array_map + implode

$string = "foo|foo|foo|foo|foo|foo";
$array = stringSplit($string,"|",2);
var_dump($array);

Output

array
  0 => string 'foo|foo' (length=7)
  1 => string 'foo|foo' (length=7)
  2 => string 'foo|foo' (length=7)

Function used

function stringSplit($string, $search, $chunck) {
    return array_map(function($var)use($search){return implode($search, $var); },array_chunk(explode($search, $string),$chunck));
}
Sign up to request clarification or add additional context in comments.

1 Comment

could you put that in a function please?

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.