Looking for a way to take a string and replace every single with two symbols and back again

StackOverflow https://stackoverflow.com/questions/22109993

  •  18-10-2022
  •  | 
  •  

Pergunta

I'm trying to figure out a way to take an imported string and replace every character with 2 specified characters and then be able to take the output and run it through another function to bring back the original string.

this is an example of the conversion i'm looking to do

@  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O      From
AF AE AD AC AB AA A9 A8 A7 A6 A5 A4 A3 A2 A1 A0     To

   !  "  #  $  %  &  '  (  )  *  +  ,  -  .  /      From
CF CE CD CC CB CA C9 C8 C7 C6 C5 C4 C3 C2 C1 C0     To

I would think this would be something along 2 arrays with the to and from in the same order similar to this?

$before = array("A","B","C","D","E");
$after = array("AE","AD","AC","AB","AA");

echo someFunction("CAB"); // outputs "ACAEAD"

but I can't figure out the best way to go about this. What would be the best way to do this?

Foi útil?

Solução 2

You can use strtr.

$trans = array("A" => "AE","B" => "AD", "C"=>"AC","D"=>"AB","E"=>"AA");
echo strtr("CAB", $trans); // outputs "ACAEAD"

For the reverse function, just array_flip the original array.

$trans2 = array_flip($trans);
echo strtr("ACAEAD", $trans); // outputs "CAB"

Outras dicas

try like this:

make an key=>value pairs array by array_combine() and use strtr()

$before = array("A","B","C","D","E");
$after = array("AE","AD","AC","AB","AA");
$array =  array_combine($before,$after); // make key value pairs array

echo someFunction($array,"CAB");

function someFunction($arr,$string) {
 return strtr($string, $arr);

 }

OUTPUT: ACAEAD

demo

You can actually pass arrays to str_replace

$someString = "abc";
$search = array('a','b','c');
$replace = array('ae','ad','ac');
$someString = str_replace($search, $replace, $someString);

EDIT https://eval.in/107493

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top