Strings\wrap()

transformer returns Closure pure
(string, string?) → (string → string)
At a glance — Bind the wrapper strings once; reuse to wrap any input.

Allows you to create a function which wraps any passed string with opening and closing strings. 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 string       $opening Added to the start of the string (and end, if no $closing supplied)
  * @param string|null  $closing Added to the end of the string (optional)
  * @return Closure(string):string
  */
 Strings\wrap(string $opening, ?string $closing = null ): Closure

Returned Closure

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

/**
  * @param string $toWrap  The string to be wrapped
  * @return string         The wrapped string
  * @psalm-pure
  */ 
$function(string $toWrap): string

Examples

Partial Application

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

// Create the closure to wrap any string with a <span> tag
$makeSpan = Strings\wrap('<span>', '</span>');

// Called as a function.
echo $makeSpan('Hello'); // <span>Hello</span>

// Used in a higher order function.
$array = array_map( $makeSpan, ['Hello', 'World']);
print_r($array); // [<span>Hello</span>, <span>World</span>]

Curried

This can be called inline using currying.

echo Strings\wrap('##')('Hello'); // ##Hello##

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\wrap('<p>', '</p>'), 
   ['Hello', 'World']
);
print_r($array); // [<p>Hello</p>, <p>World</p>] 

Details

Strings Functions

Releated String manipulation Functions