Home  >  Q&A  >  body text

Avoid replacing strings repeatedly, replace only once

I'm trying to replace a string but it works like a loop

$especiais = ["b", "c", "k", "g", "j", "d", "f", "a", "e", "m", "i", "y", "h", "l", "p", "q", "n", "x", "o", "r", "z", "u", "v", "w", "s", "t"];

$certo =  ["pn", "veh", "veh", "ged", "ged", "gal", "or", "un", "graph", "tal", "gon", "gon", "na", "ur", "mals", "ger", "drux", "pal", "med", "don", "ceph", "van", "van", "van", "fam", "gisg"];

$resultado = str_replace($especiais, $certo, $phrase);

Sample code returns: OL Returns medvanandon

The exact result I need is OL returns MEDUR

I need each letter to be replaced by the corresponding letter exactly, but in this code, the replacement is repeated multiple times.

P粉257342166P粉257342166382 days ago507

reply all(1)I'll reply

  • P粉021553460

    P粉0215534602023-09-07 00:38:42

    There is a notice in the str_replace() PHP documentation with the following content:

    Instead, I recommend using strtr(), which allows you to pass a "replacement" array in the format (from => to), as in the following example:

    $replace = [
        'b' => 'pn',
        'c' => 'veh',
        'k' => 'veh',
        'g' => 'ged',
        'j' => 'ged',
        'd' => 'gal',
        'f' => 'or',
        'a' => 'un',
        'e' => 'graph',
        'm' => 'tal',
        'i' => 'gon',
        'y' => 'gon',
        'h' => 'na',
        'l' => 'ur',
        'p' => 'mals',
        'q' => 'ger',
        'n' => 'drux',
        'x' => 'pal',
        'o' => 'med',
        'r' => 'don',
        'z' => 'ceph',
        'u' => 'van',
        'v' => 'van',
        'w' => 'van',
        's' => 'fam',
        't' => 'gisg',
    ];
    
    $phrase = 'ol';
    
    echo strtr($phrase, $replace);

    This will give you the output you expect, as shown below:

    medur

    Demo: https://tehplayground.com/5YSxPYZfreiPTz9K

    reply
    0
  • Cancelreply