I want to have a short and easy way to replace character:
A to B, B to C, Z to A, ... in PHP.
I already have tried this:
$pwd = "Abc";
for($char = ord('A'); $char <= ord('Z'); $char++) {
$newc = $char+1;
if($newc > 90)
$newc = 65;
$pwd = str_replace(chr($char), chr($newc), $pwd);
$pwd = str_replace(chr($char+32), chr($newc+32), $pwd);
}
echo $pwd;
But when I use it I only get "Aaa"...
$str = 'a';
echo ++$str; // prints 'b'
This should work for you:
Here I simply str_split()
the string into an array and then go through each character with array_map()
. There I check if it is either a lowercase or an uppercase letter.
If yes I simply return the character incremented and if it goes over zZ
I just return aA
.
At the end I simply implode()
the array again into a string.
<?php
$str = "Aac";
$str = implode("", array_map(function($v){
if(ord($v) >= 65 && ord($v) <= 90)
return (++$v > 90 ? char(65) : $v);
elseif(ord($v) >= 97 && ord($v) <= 122)
return (++$v > 122 ? char(97) : $v);
else
return $v;
}, str_split($str)));
echo $str;
?>
output:
Bbd
Here is a simple loop that does the job:
// A function to replace uppercase characters in a string with
// the next letter in the alphabet
function replace($str) {
$len = strlen($str);
for ($i = 0; $i < $len; ++$i) {
// Check if the current character is an uppercase letter
if (ctype_upper($str[$i])) {
if ($str[$i] == 'Z') {
// If it is a "Z", simply make it an "A"
$str[$i] = 'A';
}
else {
// If it is anything else, just get the next
// character from the ASCII table
$str[$i] = chr(ord($str[$i]) + 1);
}
}
}
return $str;
}
You can use it like this:
echo replace('HELLO, YOU! ABCDEFGH...XYZ');
This will output IFMMP, ZPV! BCDEFGHI...YZA
as expected.
You can read more about ctype_upper
here: http://php.net/ctype-upper - it is basically a function to check whether a string or a character is uppercase or not.
chr
and ord
just convert an ASCII code to a character and vice-versa. Read the official documentation if necessary: http://php.net/ord and http://php.net/chr.