Skip to content

Instantly share code, notes, and snippets.

@xZero707
Last active February 11, 2019 11:02
Show Gist options
  • Save xZero707/69a611dea3f3eb214fc0aaf40cc0338f to your computer and use it in GitHub Desktop.
Save xZero707/69a611dea3f3eb214fc0aaf40cc0338f to your computer and use it in GitHub Desktop.
str_replace on steroids
<?php
namespace NorthernLights\Util;
/**
* Map/replace string accordingly to supplied character map
* Note:
* There is certain overhead because we use 4 function calls main -> mapper -> array_keys -> array_values
* versus that it can be done with just single str_replace()
* However, accordingly to benchmarks, difference becomes noticeable only after 1 000 000 iterations (~300ms slower)
*
* @param string $subject
* @param array $replMap
* - Schema: "target" => "replacement"
*
* @param callable|null $mapper
* - Mapper function. Must accept arguments array, array, string and return string
* - Default mapper function is str_replace
*
* @author Aleksandar Puharic <xzero@elite7hackers.net>
*
* @return string
*/
function strMap($subject, array $replMap, callable $mapper = null)
{
// Return immediately if empty
if ($subject === '') {
return '';
}
// Return immediately if empty
if ($replMap === []) {
return $subject;
}
$mapper = ($mapper === null) ? 'str_replace' : $mapper;
return $mapper(
array_keys($replMap),
array_values($replMap),
$subject
);
}
@xZero707
Copy link
Author

Usage:

<?php

use function NorthernLights\Util\strMap;

$test = strMap('Hello {{you}}! It\'s a {{weekday}} today.', [
            '{{you}}' => 'world',
            '{{weekday}}' => date('l')
]);

var_dump($test);

Example above shows something like "Hello world! It's a Sunday today."
Note: Wrapping in {{string}} is not required.
It will work like standard str_replace unless different callable is supplied.

Doing exactly the same with str_replace(), yields quite ugly code:

<?php

$test = str_replace([
    '{{you}}',
    '{{weekday}}'
], [
    'world',
    date('l')
], 'Hello {{you}}! It\'s a {{weekday}} today.');

var_dump($test);

To make the code more readable, I could have assigned arrays to variables, but that's impractical, and would yield anything but elegant code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment