In the documentation for preg_replace is says you can use indexed arrays to replace multiple strings. I would like to do this with associative arrays, but it seems to not work.
Does anyone know if this indeed does not work?
In the documentation for preg_replace is says you can use indexed arrays to replace multiple strings. I would like to do this with associative arrays, but it seems to not work.
Does anyone know if this indeed does not work?
Do you want to do this on keys or the keys and values or just retain the keys and process the values? Whichever the case, array_combine()
, array_keys()
and array_values()
can achieve this in combination.
On the keys:
$keys = array_keys($input);
$values = array_values($input);
$result = preg_replace($pattern, $replacement, $keys);
$output = array_combine($result, $values);
On the keys and values:
$keys = array_keys($input);
$values = array_values($input);
$newKeys = preg_replace($pattern, $replacement, $keys);
$newValues = preg_replace($pattern, $replacement, $values);
$output = array_combine($newKeys, $newValues);
On the values retaining keys:
$keys = array_keys($input);
$values = array_values($input);
$result = preg_replace($pattern, $replacement, $values);
$output = array_combine($keys, $result);
All of these assume a function something like:
function regex_replace(array $input, $pattern, $replacement) {
...
return $output;
}
If I understand this correctly, what you want is:
$patterns = array_keys($input);
$replacements = array_values($input);
$output = preg_replace($patterns,$replacements,$string);