Strings\split()

transformer returns Closure pure
(string, int) → (string → string[])
At a glance — Wraps explode().

Allows you to create a function which can be used to split a string with a defined starting and ending char index. These can either be used as part of a Higher Order Function such as array_map() or as part of a compiled/pipe function.

/**
  * @param non-empty-string $separator The char to split by.
  * @param int $limit The number of groups to split into.
  * @return Closure(string):array<string> The parts
  */
 Strings\split(string $separator, int $limit = PHP_INT_MAX): Closure

Returned Closure

When Strings\split() is called, it returns the following Closure which can be used like a regular function.

/**
  * @param string $string The string to be split
  * @return array<int, string>
  * @psalm-pure
  */ 
$function(string $string): string

Examples

Partial Application

This can be used to create a simple closure which can be used as a regular function.

// Create a closure which will take the first 2 characters of a string.
$splitFirst2 = Strings\split(',', 2);  

// Called as a function.
echo $splitFirst2('Hello,World'); // [Hello, World]

// Used in a higher order function.
$array = array_map( $splitFirst2, ['Hello,World', 'Foo,Bar']);
print_r($array); // [[Hello, World], [Foo, Bar]]

Curried

This can be called inline using currying.

echo Strings\split('-')('Hello-World'); // [Hello, World]

Inlined with Higher Order Function

If you are not planning on reusing the Closure created, you can just call it inline with a higher order function as its callable.

$array = array_map( Strings\split('-'), ['Hello-World', 'Foo-Bar']);

 print_r($array); // [[Hello, World], [Foo, Bar]]

Details

Strings Functions

Releated String transform Functions