Empty Space in PHP String Explode

Asked

Viewed 92 times

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;
    ?>

2 answers

3

On the problem with the spaces, inspect the variable $letras, will realize that it generates two $values "" (empty) for every three spaces. This is because the spaces are being used by split / explode, then it takes everything between the spaces. For three sequent "empty" spaces, between them, the return is "" (emptiness).

Although there are other ways, I preferred to keep his reasoning, adding in foreach:

  • for every time he meets a $value empty, it adds a space, otherwise it takes the value in the variable $morse.
  • in the end, it clears out unnecessary spaces by printing HEY JUDE instead of HEY JUDE.
<?php

    function morse($mensagem) {
    
        $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 = '';
        $letras = preg_split("/\s/", $mensagem);
        
        foreach ($letras as $value) {
        
            $saida .= !empty($value) ? array_search($value, $morse) : ' ';
        }
            
        return preg_replace("/\s{2,}/", " ", $saida);
    }
    
    echo morse(".... . -.--   .--- ..- -.. .");

Paying attention to the foreach, in this case, you do not need to pass the array id, since the query is based on the $value.

  • 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.

  • @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 used Ternário instead of IF ELSE and finally, I covered the code in a função which returns the result of morse code, so you can call morse('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.

1

Weverton, make it easy, make it 2 explodes: the first with 3 spaces as separator (which will divide the message into words) and a second explodes with 1 space as separator (which will divide the word into letters).

Your code would look like below. I modified the array to not need the array_search and used the ?? for the case of nonexistent morse code, it include the code itself in the output (modify as you wish).

<?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 = ".... . -.--   .--- ..- -.. .";

    //Divide mensagem em palavras
    $palavras = explode('   ', $mensagem);
    foreach ($palavras as $palavra) {
        
        //Divide palavra em "letras morse"
        $letras = explode(' ', $palavra);
        foreach ($letras as $letra)
        {
            //Converte "letra morse" para letra do alfabeto e concatena na saída
            $saida .= $morse[$letra] ?? $letra;
        }
        
        //Adiciona espaço para separar as palavras na saída
        $saida .= ' ';
    }
        
    //Tira espaço extra ao final
    $saida = trim($saida);
    
    //Exibe resultado
    echo $saida;
?>
  • Cara vale d+, I had not thought from this angle of being able to make two explodes. Very interesting, It was really worth.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.