Last active
February 11, 2019 11:02
-
-
Save xZero707/69a611dea3f3eb214fc0aaf40cc0338f to your computer and use it in GitHub Desktop.
str_replace on steroids
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
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:
To make the code more readable, I could have assigned arrays to variables, but that's impractical, and would yield anything but elegant code.