Nic Hubbard
Nic Hubbard

Reputation: 42167

Use associative arrays with preg_replace

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?

Upvotes: 2

Views: 6970

Answers (3)

TheTechGuy
TheTechGuy

Reputation: 17374

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.

Upvotes: 1

slebetman
slebetman

Reputation: 113974

If I understand this correctly, what you want is:

$patterns = array_keys($input);
$replacements = array_values($input);
$output = preg_replace($patterns,$replacements,$string);

Upvotes: 1

cletus
cletus

Reputation: 625237

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;
}

Upvotes: 9

Related Questions