我为多个字符串替换编写了一个php函数
$searchArray = array("0","9","8","7","6","5","4","3","2","1","!","@","#","$","%","^","&","*","(",")","z","x","y","w","u","v","j","i","h","g","f","e","d","c","b","a");
$replaceArray = array("1","2","3","4","5","6","7","8","9","0","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
$string='protect your php code';
echo $code=str_replace($searchArray, $replaceArray, $string);
其结果= protvxt moor psp xowv看似正确
当我改变其立场时
$string='protvxt moor psp xowv';
$searchArray = array("1","2","3","4","5","6","7","8","9","0","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
$replaceArray = array("0","9","8","7","6","5","4","3","2","1","!","@","#","$","%","^","&","*","(",")","z","x","y","w","u","v","j","i","h","g","f","e","d","c","b","a");
echo $code=str_replace($searchArray, $replaceArray, $string);
它给我这个答案= eifgecg bffi ehe cfde(这是错的)它应该正确颠倒并给出答案保护你的PHP代码
老实说,我不知道为什么php做错了
我在这里粘贴代码
http://codepad.org/xbSCieZl
请检查这个我想知道我做错了什么让我发疯
答案 0 :(得分:1)
您的数组应包含相同的字符。
第一次转换不会将字符'pro'从'protect'更改
但逆转确实如此。
编辑:对不起这个答案是错误的,因为我不知道以下的问题,詹姆斯在上面提到:“这一般不会奏效。你的测试字符串很幸运。如果你试图编码字符串“123”你将获得“123”,因为1变为零,然后零变为1,等等。请参阅str_replace gotchas - James“
您可以使用上面的建议strtr()
$search = "abcdefghijklmnopqrstuvwxyz";
$replace = "zabcdefghijklmnopqrstuvwxy";
$string='protect your php code';
echo $code=strtr($string, $search, $replace);
echo '<br>';
echo strtr($code, $replace, $search);
输出:
oqnsdbs xntq ogo bncd
保护您的PHP代码
编辑:
另外,你可以生成你的字符串并随机化:
$search = implode("",range("a","z")).implode("",range("0","9"));
$replace = str_shuffle($search);