Morse code has been on my mind every now and then for the past several years. I don't write as much code as I used to since I left the software development industry, but today I decided it was time to write functions to encode and decode morse.
First, let's define an array to map the encodings for each character.
- $morse = array(
- " " => "/",
- "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" => "--..",
- "0" => "-----",
- "1" => ".----",
- "2" => "..---",
- "3" => "...--",
- "4" => "....-",
- "5" => ".....",
- "6" => "-....",
- "7" => "--...",
- "8" => "---..",
- "9" => "----.",
- "." => ".-.-.-",
- "," => "--..--",
- "?" => "..--..",
- "'" => ".----.",
- "!" => "-.-.--",
- "/" => "-..-.",
- "(" => "-.--.",
- ")" => "-.--.-",
- "&" => ".-...",
- ":" => "---...",
- ";" => "-.-.-.",
- "=" => "-...-",
- "+" => ".-.-.",
- "-" => "-....-",
- "_" => "..--.-",
- "\"" => ".-..-.",
- "$" => "...-..-",
- "@" => ".--.-.",
- );
- function morseEncodeMessage($message)
- {
- global $morse;
- $result = "";
- for ($i = 0; $i <= strlen($message) - 1; $i++)
- {
- $character = strtoupper(substr($message, $i, 1));
- $result .= (array_key_exists($character, $morse) ? $morse[$character] : "........") . " ";
- }
- $result = rtrim($result);
- return $result;
- }
- function morseDecodeMessage($message)
- {
- global $morse;
- $result = "";
- $characters = explode(" ", $message);
- foreach ($characters as &$character)
- {
- $result .= in_array($character, $morse, true) ? array_search($character, $morse, true) : "ERROR";
- }
- unset($character);
- return $result;
- }
- function morseTest($message)
- {
- $testInput = $message;
- echo "Input: " . strtoupper($testInput) . "\n";
- $testEncoded = morseEncodeMessage($testInput);
- echo "Encoded: " . $testEncoded . "\n";
- $testDecoded = morseDecodeMessage($testEncoded);
- echo "Decoded: " . $testDecoded . "\n";
- echo "Result: Test " . ($testDecoded == strtoupper($testInput) ? "successful" : "failed") . "!\n";
- }