Search code examples
phparraysrandomreplacemapping

Replace specified letters with randomly selected strings from an array dedicated to the found letter


I have a few letters; for example a, b, c, d and e.

For each one of them, I have sets of two-character values like this:

a -> fg, dz, gc, bg

b -> zt, hg, oq, vg, gb

c -> lt, pr, cs, sh, pr

d -> kt, nt, as, pr

e -> zd, ke, cg, sq, mo, ld

Here comes the question:

I would like to get a random value for each time for example: dcbae and for this the ultimate output should be something like this: ntshztdzld or asltvggcmo, etc.

(After generating a random string with the characters above (between a-e), it should generate another string that contains random values those are related with the each character.


Solution

  • Well, you would first create a map:

    $map = Array(
        "a" => Array("fg","dz","gc","bg"),
        "b" => Array("zt","hg","oq","vg","gb"),
        "c" => Array("lt","pr","cs","sh","pr"),
        "d" => Array("kt","nt","as","pr"),
        "e" => Array("zd","ke","cg","sq","mo","ld")
    );
    

    I notice that you have the same pair "pr" several times - if you want this encoding to be reversible, avoid duplicates.

    Anyway, once you have that it's easy enough to loop through your input string and get a random output:

    $input = "dcbae";
    $len = strlen($input);
    $output = "";
    for( $i=0; $i<$len; $i++) {
        $entry = &$map[$input[$i]];
        if( isset($entry)) $output .= $entry[mt_rand(0,count($entry)-1)];
        else $output .= "??";
    }
    

    $output is the result.