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): ClosureWhen Strings\translateWith() is called, it returns the following Closure which can be used like a regular function.
/**
* @param string $haystack
* @return string
*/
$function ($haystack): stringThis 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']This can be called inline using currying.
echo Strings\translateWith(['foo' => 'bar])( 'foo is foo'); // bar is barIf 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']