You can't use str_replace()
here because, as you've mentioned, it may replace characters more than one time as you iterate over you array. Instead you should iterate over the characters of your string and subtitute each character separately, by index.
for ($i = 0; $i < strlen($text); $i++) {
$text[$i] = $letters3[array_search($text[$i], $letters2)];
}
While you could use two arrays for the alphabet and substitution characters, I think an associative array is a more appropriate structure for this task.
$text = 'abcdzwxy';
$letters2 = ['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'];
$letters3 = ['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'];
$map = array_combine($letters2, $letters3);
for ($i = 0; $i < strlen($text); $i++) {
$text[$i] = array_search($text[$i], $map);
}
echo $text;
If the string contains Hebrew or other UTF-8 characters you can't iterate over it because a character may contain more than one bytes. In this case you could use preg_split()
to create an array of UTF-8 characters.
$text = preg_split('//u', $text, null, PREG_SPLIT_NO_EMPTY);
(code taken from this answer)
The rest of the code is mostly the same, but now $text
is an array and it must be converted back to string.
function str_to_array($str) {
return preg_split('//u', $str, null, PREG_SPLIT_NO_EMPTY);
}
$text = "תשר";
$text = str_to_array($text);
$alphabet = str_to_array("אבגדהוזחטיךכלםמןנסעףפץצקרשת");
$map = array_combine($alphabet, array_reverse($alphabet));
for ($i = 0; $i < sizeof($text); $i++) {
$char = array_search($text[$i], $map);
if ($char) {
$text[$i] = $char;
}
}
$text = implode($text);