# 简单加密：PHP中需要的解密算法

• cryptography
• php

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`.

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

#### 4条回答

• 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

点赞 评论 复制链接分享
• If you don't want to change your strings try this

``````\$count = 0;
while(true){
\$var = "var".++\$count;
if(\$\$var){
\$\$var = \${\$var};
}
else break;
}
``````
点赞 评论 复制链接分享
• 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
``````
点赞 评论 复制链接分享
• 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.

点赞 评论 复制链接分享