Simple cryptography: decryption algorithm needed in PHP

给你一囗甜甜゛ 提交于 2020-01-01 07:32:10

问题



I'm working the webpage that I have some text like this:
AA,BB,CC,A1,B2,C3
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:

<?php
    $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:
ABC123
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.


回答1:


Full working script with sample encryption catalog given here.

<?php
$encript = array(
'a'=>'GG', 
'b'=>'HH',  
'c'=>'II',

'A'=>'DD',  
'B'=>'EE',
'B'=>'FF',

'1'=>'AA', 
'2'=>'BB',
'3'=>'CC');


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: http://sugunan.net/demo/str1.php




回答2:


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.




回答3:


Try this

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

Output

ABC123



回答4:


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

$count = 0;
while(true){
    $var = "var".++$count;
    if($$var){
        $$var = ${$var}[1];
    }
    else break;
}


来源:https://stackoverflow.com/questions/25555011/simple-cryptography-decryption-algorithm-needed-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!