1
I have the following problem in PHP
I need to remove the characters from a string, and then insert them in the same position. I’m currently doing so, but I’m open to suggestions.
I have an initial string: te12te
I remove the numbers from this string and store the character and position in two arrays:
$stringInicial = "te12te";
//Processo de remoção resulta em:
$arrayCaracteres = ["1", "2"];
$arrayPosicao = [2, 3];
$stringInicial = "tete";
//As letras da string passam por um processo e são alteradas seguindo uma lógica
$stringInicial = "vivi";
//Preciso agora inserir os caracteres na mesma posição
Given this information, I need to insert the removed characters at the beginning, at the same position. That is, the result should be vi12vi
EDIT: The procedure performed is the Playfair cipher, it follows the code that does this procedure:
for ($i = 0; $i < strlen($plainText); $i += 2) {
//compute coords
$x0 = array_search($plainText[$i], $this->matrix) % 5;
$y0 = intval(array_search($plainText[$i], $this->matrix) / 5);
$x1 = array_search($plainText[$i + 1], $this->matrix) % 5;
$y1 = intval(array_search($plainText[$i + 1], $this->matrix) / 5);
if ($y0 == $y1) {
//same line
$encrypted .= $this->matrix[5 * $y0 + (($x0 + 1) % 5)];
$encrypted .= $this->matrix[5 * $y1 + (($x1 + 1) % 5)];
} elseif ($x0 == $x1) {
//same column
$encrypted .= $this->matrix[5 * (($y0 + 1) % 5) + $x0];
$encrypted .= $this->matrix[5 * (($y1 + 1) % 5) + $x1];
} else {
//line and column are different
$encrypted .= $this->matrix[(5 * $y0 + $x1)];
$encrypted .= $this->matrix[(5 * $y1 + $x0)];
}
}
str_replace("te","vi",$stringInicial; https://ideone.com/cNRiC1
– user60252
This string is not always the same, I used this only to create the example.
– José Henrique Luckmann
and what is the pattern
– user60252
is an encryption cipher, and I need to ignore the numbers when encrypting. There is no default for the initial string
– José Henrique Luckmann
Will always be the numbers that will be removed and inserted?
– Woss
so it’s already a pattern
– user60252
@Andersoncarloswoss will always be numbers and special characters ()! $#@etc
– José Henrique Luckmann
Is there a better way to describe how this change of letters works? I was thinking here and I couldn’t think of a beautiful way to do it. All of them seemed gambiarras. Who knows it is possible to integrate the two parts and do something better.
– Woss
@Andersoncarloswoss the process is the cipher of Playfair, I edited to try to show how it is
– José Henrique Luckmann