I'm writing a function that decodes a morse code message to plain text. The problem I'm running into, is that it doesn't add spaces where needed. Keep in mind that every morse code character/letter, is separated with a blank space and every full word, is separated by 3 spaces. I want the function to add a single blank space to the plain text when it detects 3 blank spaces in a row in the morse code. I can't figure it out so I've come here.
Here is the function as it is now.
public function decode($morseCode)
{
// 1 space between characters, 3 spaces between words
// split the string
$morseArray = preg_split('/\s+/', $morseCode, -1);
$plainText = '';
$blankSpaceCount = 0;
// set each string as a morse code character
foreach ($morseArray as $morseChar)
{
if ($morseChar != ' ')
{
// check if the morsecode character is in the array
if(isset($this->plainTextsByMorseCode[$morseChar]))
{
// if it is, convert it to the corresponding plain text
$plainText .= $this->plainTextsByMorseCode[$morseChar];
$blankSpaceCount = 0;
}
}
else {
$blankSpaceCount++;
if ($blankSpaceCount === 3)
{
$plainText .= ' '; // Append a single blank space
$blankSpaceCount = 0;
}
}
}
return trim($plainText);
}
If it helps, the phrase I'm trying to decode is as follows:
-.-- --- ..- ... .... .- .-.. .-.. -. --- - .--. .- ... ...
It says "YOU SHALL NOT PASS" and you can clearly see the triple blank spaces between the words and the singular blank space between the letters.