Avoid replacing strings repeatedly, replace only once
P粉257342166
P粉257342166 2023-09-06 11:10:09
0
1
728

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粉257342166
P粉257342166

reply all(1)
P粉021553460

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template