1

I have a string containing comma-separated numbers and I also have an associative array in PHP containing unique numbers. What I want to achieve is to create a new string that contains only the exact match replacements based on the array. Here is my code so far:

    <?php
$replacements = array(
    '12' => 'Volvo',
    '13' => 'BMW',
    '132' => 'Alfa Romea',
    '156' => 'Honda',
    '1536' => 'Tesla',
    '2213' => 'Audi'
);
$str ="12,13,132,2213";
echo str_replace(array_keys($replacements), $replacements, $str);
?>

The only problem is that the output is this:

Volvo,BMW,BMW2,22BMW

instead of this:

Volvo,BMW,Alfa Romeo,Audi

How can I achieve exact match search and replace in this function? Is there a fastest PHP solution for this problem? Thanks, belf

belf
  • 13
  • 2
  • This happens because of the order in which these replacements happen. It finds `13` in `132` (and replaces that part with BMW), before it even gets to looking for `132`. You can avoid this, if you simply sort your array by descending key lengths. If 132 gets replaced before it starts looking for 13, then you do not have this problem. – CBroe Mar 12 '21 at 08:03
  • From the duplicate `echo strtr( $str, $replacements);` – Nigel Ren Mar 12 '21 at 08:04
  • Great, thanks Nigel! – belf Mar 12 '21 at 10:06

2 Answers2

0

You may use this very simple, straight-forward, and easy to understand code:

$result = [];
foreach (explode(',', $str) as $id) {
    $result[] = isset($replacements[$id]) ? $replacements[$id] : $id;
}
$str = implode(',', $result);
0

Another one-liner. Combine explode the string keys, and flip it to serve as keys using array_flip, then finally, array_intersect_key to combine them by key. implode the remaining values combined:

$cars = implode(', ', array_intersect_key($replacements, array_flip(explode(',', $str))));
Kevin
  • 41,694
  • 12
  • 53
  • 70