How to replace a letter in a string with a new letter that will not be updated

后端 未结 3 526
攒了一身酷
攒了一身酷 2020-12-12 02:08

Lets say I have some code:

$text = $_POST[\'secret\'];

$replaces = array(
        \'a\' => \'s\',
        \'b\' => \'n\',
        \'c\' => \'v\',
          


        
相关标签:
3条回答
  • 2020-12-12 02:11
    <?php
    $text = $_POST['secret'];
    
    $replaces = array(
        'a' => 's',
        'b' => 'n',
        'c' => 'v',
        'd' => 'f',
        'e' => 'r',
        'f' => 'g',
        'g' => 'h',
        'h' => 'j',
        'i' => 'o',
        'j' => 'k',
        'k' => 'l',
        'l' => 'a',
        'm' => 'z',
        'n' => 'm',
        'o' => 'p',
        'p' => 'q',
        'q' => 'w',
        'r' => 't',
        's' => 'd',
        't' => 'y',
        'u' => 'i',
        'v' => 'b',
        'w' => 'e',
        'x' => 'c',
        'y' => 'u',
        'z' => 'x',
    );
    
    for( $i=0,$l=strlen($text);$i<$l;$i++ ){
        if( isset($replaces[$text[$i]]) ){
            $text[$i] = $replaces[$text[$i]];
        }
    }
    
    echo "You're deciphered message is: ".$text;
    
    ?>
    
    <form action="" method="post">
    <p>Enter the secret message: <input name="secret" type="text"/></p>
    <input class="button" type="submit" name="submit" value="Submit"/>
    
    </form>
    
    0 讨论(0)
  • 2020-12-12 02:11

    this will be your solution

       $text1 = '';
       for($i=0; $i<strlen($text); $i++)  {
         $text1 .= $replaces[$text[$i]];
       }
    
       echo $text1;
    

    or else you can use like this

    $text = strtr($text,$replaces);
    
    0 讨论(0)
  • 2020-12-12 02:20

    In the PHP Manual it's clearly explained your problem, at the end of the page they advice to use strtr() which does exactly what you want.

    Replace

      $text = str_replace(array_keys($replaces),array_values($replaces),$text);
    

    with

      $text = strtr($text,$replaces);
    

    which does exactly what you want, it replaces one character with another character.

    The documentation of strtr() is here: http://www.php.net/manual/en/function.strtr.php

    0 讨论(0)
提交回复
热议问题