2

In the documentation for preg_replace it 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?

Toto
  • 89,455
  • 62
  • 89
  • 125
Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412
  • See this link [Pre_REPLACE with Asscoiate Array][1] [1]: http://stackoverflow.com/questions/17979011/use-preg-replace-to-replace-whole-words-using-associative-array – toneexcel web Mar 09 '15 at 02:42

3 Answers3

9

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;
}
cletus
  • 616,129
  • 168
  • 910
  • 942
1

If I understand this correctly, what you want is:

$patterns = array_keys($input);
$replacements = array_values($input);
$output = preg_replace($patterns,$replacements,$string);
slebetman
  • 109,858
  • 19
  • 140
  • 171
1

Spent quite bit of time on this so will add my answer

$str = "CT is right next to NY";

$list = array('CT'=>'connenticut', 'NY'=>'New York', 'ME' => 'Maine');
$list = get_json();

$pattern = array_keys($list);
$replacement = array_values($list);

foreach ($pattern as $key => $value) {
    $pattern[$key] = '/\b'.$value.'\b/i';
}

$new_str = preg_replace( $pattern,$replacement,  $str);

Make sure you use /delimiters/ for regex pattern matching. \b is for word boundary.

TheTechGuy
  • 16,560
  • 16
  • 115
  • 136