2
Hello, I’m having problems using a EXPLODE in a PHP String. I used a space as delimiter but I need to pick up when there are 3 spaces followed as a position in the Array. It is an exercise of a morse code coder. The word is formed ok but the space between them I cannot place in the output string. If I put another delimiter it would work perfectly, but for the exercise I can’t use another one, and I need to be able to check when it’s just a space or when it’s 3. The code should take morse code and turn it into text...
Thank you very much.
<?php
$morse = [
' ' => ' ',
'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' => '--..'
];
$saida = '';
$mensagem = ".... . -.-- .--- ..- -.. .";
$letras = explode('', $mensagem);
foreach($letras as $i => $value)
{
$saida .= array_search($letras[$i],$morse);
}
echo $saida;
?>
Good morning Weslley. I didn’t understand 100% yet the resolution you used, I’m still beginner in programming. This is a Codewars exercise, I used as a base a code I found searching but ended up locking in time to ensure that it returned the words with space. He would return "HEYJUDE;' instead of "HEY JUDE" But I will study the code better. I thank you too much, thanks even.
– Weverton Júnior
@Wevertonjúnior What don’t you understand? As you are starting, I used some "new" things in the script:
regex(a way to check if the text obeys a rule - (/\s/brings all the spaces and/\s{2,}/always brings where occur two or more spaces in a row)). I also usedTernárioinstead ofIF ELSEand finally, I covered the code in afunçãowhich returns the result of morse code, so you can callmorse('qualquer código morse'), As many times as you want. If you want me to explain some specific part better, you can comment here, anything I add in the reply.– Weslley Araújo