Skip to content

Instantly share code, notes, and snippets.

@Dinir
Created September 20, 2017 07:04
Show Gist options
  • Save Dinir/9974da502938896c6e80cbc01e749077 to your computer and use it in GitHub Desktop.
Save Dinir/9974da502938896c6e80cbc01e749077 to your computer and use it in GitHub Desktop.
Replace multiple parts of a string at once using `mb_ereg_replace`.
<?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);
}
};
@eshoberg
Copy link

eshoberg commented Mar 28, 2019

This is far from a 1:1 of preg_replace. But you did get me started toward something closer.

       $mb_ereg_bulk_replace = function ($patterns, $replacements, $string) {
		$patterns     = is_string($patterns) ? [$patterns] : $patterns;
		$replacements = is_string($replacements) ? [$replacements] : $replacements;
		$options = [];
		foreach ($patterns as $key => $pattern) {
			$pattern = explode('/', $pattern);
			$optionString = array_pop($pattern);
			$options[] = empty($optionString) ? null : $optionString;
			array_shift($pattern);
			$patterns[$key] = implode('/', $pattern);
			$replacements[$key] = isset($replacements[$key]) ? $replacements[$key] : "";
		}
		$replace_rule = array_combine($patterns, $replacements);
		$options = array_combine($patterns, $options);
		return array_reduce($patterns, function ($string, $v) use ($replace_rule, $options) {
			return mb_ereg_replace($v, $replace_rule[$v], $string, $options[$v]);
		}, $string);
	};

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.

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