Strings\findToReplace()

transformer returns Closure pure
string → (string → (string → string))
At a glance — A double curry — bind the needle once, then spawn any number of replacement-bound Closures that share the same target. Wraps str_replace().

Creates a double-curried find-and-replace. Binding the substring to find returns a Closure awaiting the replacement; binding the replacement returns the Closure that performs the replacement on a subject string. Useful when the same target needs to be swapped for several different values.

/**
  * @param string $find Value to look for
  * @return Closure(string):Closure
  */
Strings\findToReplace(string $find): Closure

Returned Closure

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

/**
  * @param string $replace value to replace with
  * @return Closure(string):string
  */
$function (string $replace): Closure

Examples

Partial Application

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

// First bind the needle — the returned Closure awaits a replacement.
$replaceFoo = Strings\findToReplace('foo');

// Now bind any number of replacements, each one is its own reusable string function.
$fooToBar = $replaceFoo('bar');
$fooToBaz = $replaceFoo('baz');

echo $fooToBar('its foo'); // its bar
echo $fooToBaz('its foo'); // its baz

// Either of the resulting Closures can be used in a higher order function.
$array = array_map($fooToBar, ['one foo', 'two foo', 'three foo']);
print_r($array); // ['one bar', 'two bar', 'three bar']

Curried

This can be called inline using currying.

// All three arguments supplied inline — find, replace, subject.
echo Strings\findToReplace('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.

// Skip the intermediate variables and drop the callable straight into a HOF.
$array = array_map(Strings\findToReplace('foo')('bar'), ['Its foo', 'The foo is']);
print_r($array); // ['Its bar', 'The bar is']

Details

Strings Functions

Releated String manipulation Functions