Created
September 20, 2017 07:04
-
-
Save Dinir/9974da502938896c6e80cbc01e749077 to your computer and use it in GitHub Desktop.
Replace multiple parts of a string at once using `mb_ereg_replace`.
This file contains hidden or 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 | |
/** | |
* It let you do what you can do with `preg_replace` with `mb_ereg_replace`. | |
* | |
* replacing multiple strings at once. | |
* | |
* @param array $pattern | |
* @param array $replacement | |
* @param $string | |
* | |
* @return bool|string | |
*/ | |
$mb_ereg_bulk_replace = function ($pattern, $replacement, $string) { | |
if (count($pattern) !== count($replacement)) { | |
return false; | |
} else { | |
$replace_rule = array_combine($pattern, $replacement); | |
return array_reduce($pattern, function ($string, $v) use ($replace_rule) { | |
$string = mb_ereg_replace($v, $replace_rule[$v], $string); | |
return $string; | |
}, $string); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is far from a 1:1 of preg_replace. But you did get me started toward something closer.
Note that some supplied modifiers might not be available in mb_ereg_replace, namely u (as it was/is unnecessary).
Encoding safe string sanitation is built into Elleus where I used this function.
Side note. mb_ereg_replace does not accept appended and pre-pended
"/ /"
slashes Modifiers and this script I've posted here only handles the slash version of modifiers that can be used with preg_replace.