【问题标题】:How to replace a letter in a string with a new letter that will not be updated如何用不会更新的新字母替换字符串中的字母
【发布时间】:2011-12-22 13:28:00
【问题描述】:

假设我有一些代码:

$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',

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

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

在这里,用户输入一个秘密消息,然后将字符替换为新字符。对于键盘上的每个字母,它都会替换为右侧的字母。

例如。如果用户输入“gwkki”,输出将是“hello”。 然而,上面的代码输出 aeaae 而不是 hello。它输出“aeaae”。这是因为字母 h 变为 j,然后 j 变为 k,然后 k 变为 l,然后 l 变为 a。以此类推其他字母。有没有什么办法可以让文字被扫描改一次??

【问题讨论】:

  • @Abel 因为 user1064028 用键盘上的字符替换字符,而不是字母表

标签: php string str-replace


【解决方案1】:

在 PHP 手册中,它清楚地解释了您的问题,在页面末尾,他们建议使用 strtr(),这正是您想要的。

替换

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

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

这正是您想要的,它将 one 字符替换为 another 字符。

strtr() 的文档在这里:http://www.php.net/manual/en/function.strtr.php

【讨论】:

  • 出色的解决方案,我知道某处必须有“翻译”功能。比 for 循环更具可读性。
【解决方案2】:
<?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>

【讨论】:

  • 啊,我讨厌这个 for/if/isset/bracket-wars 构造
  • 据我所知,此解决方案要快得多。出于某种原因,strtr() 的实现速度很慢。
【解决方案3】:

这将是您的解决方案

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

   echo $text1;

否则你可以这样使用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多