2014-08-28 17:49


  • cryptography
  • php

I'm working the webpage that I have some text like this:
And I want some code to replace the the word (like AA) to the string that saved in variable for example this is my php variable:

    $var1 = "A"; //For AA
    $var2 = "B"; //For BB 
    $var3 = "C"; //For CC
    $var4 = "1"; //For A1
    $var5 = "2"; //For B2
    $var6 = "3"; //For C3

And the text AA,BB,CC,A1,B2,B3 will be like this:
How can I do this with php?

In summery I need a decryption algorithm for a cypher text of AA,BB,CC,A1,B2,C3 to be converted as plan text of ABC123.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • doupike2351 doupike2351 7年前

    Full working script with sample encryption catalog given here.

    $encript = array(
    function decrypt($str,$encript)
        $decript = array_flip($encript);
        $str_arr = explode(",",$str);
        $dec = "";
        foreach($str_arr as $val)
            $dec .= $decript[strtoupper(trim($val))];
        return $dec;
    function encrypt($str,$encript)
        $str_arr = str_split($str);
        $dec = "";
        foreach($str_arr as $val)
            $dec .= $encript[trim($val)].",";
        return $dec;
    $cypher = "AA,BB,DD,CC,EE,FF,GG,HH";
    $text = "Ab1Ca";
    echo decrypt($cypher,$encript);
    echo "<br/>";
    echo encrypt($text,$encript);
    • First we have to create the mapping for each character as associative array.
    • In decrypt function first we have to flip the array.
    • Then have to loop through each encoding string and build the real text from flipped array.
    • In encryption split the string as single letter array.
    • Loop through the array and build encryption using the mapping array.

    The working out put available at following url:

    点赞 评论 复制链接分享
  • duanjing2013 duanjing2013 7年前

    If you don't want to change your strings try this

    $count = 0;
        $var = "var".++$count;
            $$var = ${$var}[1];
        else break;
    点赞 评论 复制链接分享
  • dpgbh20688 dpgbh20688 7年前

    Try this

    $str = 'AA,BB,CC,A1,B2,C3';
    $arr = explode(',', $str);
    $newStr = '';
    foreach($arr as $val){
        $newStr .= substr($val,1,1);
    echo $newStr;


    点赞 评论 复制链接分享
  • dousi4900 dousi4900 7年前

    Assuming the text is stored in $string, try this:

    $vars = array(
        'AA' => 'A',
        'BB' => 'B',
        'CC' => 'C',
        'A1' => '1',
        'B2' => '2',
        'C3' => '3',
    $string = str_replace(array_keys($vars), array_values($vars), $string);

    Also heed the warning from PHP's docs on str_replace:

    Replacement order gotcha

    Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

    点赞 评论 复制链接分享