xZero

strMap - str_replace() on steroids

Feb 14th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.18 KB | None | 0 0
  1. <?php
  2.  
  3. namespace NorthernLights\Util;
  4.  
  5. /**
  6.  * Map/replace string accordingly to supplied map
  7.  * Note:
  8.  *       There is certain overhead because we use 4 function calls main -> mapper -> array_keys -> array_values
  9.  *       versus that it can be done with just single str_replace()
  10.  *       However, accordingly to benchmarks, difference becomes noticeable only after 1 000 000 iterations (~300ms slower)
  11.  *
  12.  * @param string $subject
  13.  * @param array $replMap
  14.  *   - Schema: "target" => "replacement"
  15.  *
  16.  * @param callable|null $mapper
  17.  *   - Mapper function. Must accept arguments array, array, string and return string
  18.  *   - Default mapper function is str_replace
  19.  *
  20.  * @author Aleksandar Puharic <[email protected]>
  21.  *
  22.  * @return string
  23.  */
  24. function strMap($subject, array $replMap, callable $mapper = null)
  25. {
  26.     // Return immediately if empty
  27.     if ($subject === '') {
  28.         return '';
  29.     }
  30.  
  31.     // Return immediately if empty
  32.     if ($replMap === []) {
  33.         return $subject;
  34.     }
  35.  
  36.     $mapper = ($mapper === null) ? 'str_replace' : $mapper;
  37.  
  38.     return $mapper(
  39.         array_keys($replMap),
  40.         array_values($replMap),
  41.         $subject
  42.     );
  43. }
Advertisement
Add Comment
Please, Sign In to add comment