Good Day,
I am trying to create a morse code to text and text to morse code converter.
My code:
$letter = str_split(strtolower($_POST['text']));
$morse = $_POST['morse'];
$morsecmp = explode(" ",$morse);
$letter = implode(" ",$letter);
$mode = $_POST['sub'];
$morsecode = array(".-","-...","-.-.","-..","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",
".--.","--.-",".-.","...","-.","..-","...-",".--","-..-","-.--","--..",".");
$letters = array("a","b","c","d","f","g","h","i","j","k","l","m","n","o","p","q","r",
"s","t","u","v","w","x","y","z","e");
if($mode == "Text to Morse Code"){
$letter = str_replace($letters,$morsecode,$letter);
$translated = $letter;
}else{
for($x=0;$x<sizeof($letters);$x++){
for($y=0;$y<sizeof($morsecmp);$y++){
if($morsecode[$x] === $morsecmp[$y]){
echo $morsecode[$x]." === ".$letters[$x]."<br>";
$morse = str_replace($morsecode[$x],$letters[$x],$morse);
}
}
}
$translated = $morse;
}
sample input:
.... . .-.. .-.. --- .-- --- .-. .-.. -..
sample output:
h e ed ed o w o r ed d
expected output:
hello wolrd
My problem is that when converting from morse code to text some characters are not captured properly due to str_replace limit where it will replace all string that is similar to the needle, so if i have to replace all "." to e it will also change "...." which should be actually an h.
any help on this would be greatly appreciated.
Thank You.