Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace NorthernLights\Util;
- /**
- * Map/replace string accordingly to supplied 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 <[email protected]>
- *
- * @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
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment