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
.
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);
?>
The working out put available at following url: http://sugunan.net/demo/str1.php
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.
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
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;
}