Strings\slice()

transformer returns Closure pure
(int, int?) → (string → string)
At a glance — Bind a start (and optional length) once, reuse. Wraps mb_substr().

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 int      $start   start position (offset)
  * @param int|null $finish  end position (length)
  * @return Closure(string):string
  */
 Strings\slice(int $start, ?int $finish = null ): Closure

Returned Closure

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

/**
  * @param string $toSlice  The string to be sliced
  * @return string          The sliced string
  * @psalm-pure
  */ 
$function(string $toSlice): 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.
$sliceFirst2 = Strings\slice(0,2);  

// Called as a function.
echo $sliceFirst2('Hello'); // He
 
// Used in a higher order function.  
$array = array_map( $sliceFirst2, ['Hello', 'World']);  
print_r($array); // [He, Wo]  
 
// You can also use slice() to skip the first 5 characters of a string.  
$skipFirst5 = Strings\slice(5);
 
// Called as a function.  
echo $skipFirst5('HelloWorldBar'); // WorldBar  

Curried

This can be called inline using currying.

echo Strings\slice(0,2)('Hello'); // He  

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\slice(0,2), ['Hello', 'World']);  
print_r($array); // [He, Wo]  

Details

Strings Functions

Releated String manipulation Functions