Strings\replaceWith()

transformer returns Closure pure
(string, string) → (string → string)
At a glance — Bind both needle and replacement up front. Wraps str_replace().

Creates a function that can be used to replace any instance of a sub string, with a defined value. The created function can then reused over any string, or used as part of a Higher Order Function such as array_map().

/**
  * @param string  $find
  * @param string  $replace
  * @return Closure(string):string
  */
Strings\replaceWith(string $find, string $replace): Closure

Returned Closure

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

/**
  * @param string $source
  * @return string
  */
$function ($source): string

Examples

Partial Application

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

// Creates the Closure.
$fooToBar = Strings\replaceWith('foo', 'bar');  

// Called as a function.  
echo $fooToBar('This is foo'); // This is bar  

// Used in a higher order function.  
$array = array_map( $fooToBar, ['Its foo', 'The foo is']);  
print_r($array); // ['Its bar', 'The bar is']  

Curried

This can be called inline using currying.

echo Strings\replaceWith('Hi', 'Hello')('Hi im an example'); // Hello im an example

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\replaceWith('foo', 'bar'), ['Its foo', 'The foo is'] );
print_r($array); // ['Its bar', 'The bar is'] 

Details

Strings Functions

Releated String manipulation Functions