Strings\translateWith()

transformer returns Closure pure
map → (string → string)
At a glance — Wraps strtr() with a dictionary. Bind the mapping once, apply to many strings.

Creates a function that can be used to replace pairs of characters in a string. The created function can then reused over any string, or used as part of a Higher Order Function such as array_map().

/**
  * @param array<string, mixed> $dictionary
  * @return Closure(string):string
  */
Strings\translateWith(array $dictionary): Closure

Returned Closure

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

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

Examples

Partial Application

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

// Creates the Closure to replace foo with bar and hi with hello
$replace = Strings\translateWith(['foo' => 'bar', 'hi' => 'hello']);

// Called as a function.
echo $replace('foo is foo'); // bar is bar
echo $replace('hi im an example'); // hello im an example

// Used in a higher order function.
$array = array_map($replace, ['Its foo', 'hi you']);
print_r($array); // ['Its bar', 'hello you']

Curried

This can be called inline using currying.

echo Strings\translateWith(['foo' => 'bar])( 'foo is foo'); // bar is bar

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\translateWith(['foo' => 'bar', 'hi' => 'hello']), 
 ['Its foo', 'hi you', 'hi foo']
);
print_r($array); // ['Its bar', 'hello you', 'hello bar']

Details

Strings Functions

Releated String manipulation Functions