Echo colored in php

1

How can you leave ECHO in PHP colorful? Print in HTML, colorful letter-by-letter ex:

if (strpos($d5, '{"name":"')) {
    echo 'LIVE ->' . $a . '|' . $b . ' | C:' . $c . '';

} else {
    echo "DEAD -> $a|$b ";
}

All that gives LIVE and DEAD (printed on the screen) come out all colorful

    
asked by anonymous 24.12.2017 / 03:27

2 answers

1

Using str_split , explode or even iterate string will not work if you are using unicode (UTF-8 for example), as explained in

For this you can use preg_split with the u modifier, like this:

preg_split('//u', $texto, null, PREG_SPLIT_NO_EMPTY);

I used this response link to generate the colors, it should look like this:

<?php

function mb_text_color($texto)
{
    $letters = preg_split('//u', $texto, null, PREG_SPLIT_NO_EMPTY);

    foreach ($letters as &$letter) {
        if (trim($letter) === '') continue;

        $cor = dechex(rand(0x000000, 0xFFFFFF));
        $letter = '<span style="color:#' . $cor . '">' . $letter . '</span>';
    }

    return implode('', $letters);
}

echo mb_text_color('foo bár');

To use, you can do this:

if (strpos($d5, '{"name":"')) {
    echo mb_text_color('LIVE ->' . $a . '|' . $b . ' | C:' . $c);

} else {
    echo mb_text_color("DEAD -> $a|$b ");
}

Or so:

if (strpos($d5, '{"name":"')) {
    echo 'LIVE ->' . mb_text_color($a . '|' . $b . ' | C:' . $c);

} else {
    echo 'DEAD -> ' . mb_text_color("$a|$b ");

Or variable by variable, as you wish.

    
24.12.2017 / 04:04
1

You can do a function that generates these colored letters.

function geraLetrasColorida($palavra) {

    // Separa as letras
    $letras = str_split($palavra);

    // Percorre todas as letras
    foreach($letras as $letra) {

        // Gera uma cor aleatória baseado no hexadecimal da cor.
        $cor = dechex(mt_rand(0x000000, 0xFFFFFF));

        // Imprimi o html com a letra gerada.
        echo "<span style=\"color:#{$cor}\">".$letra."</span>";
    }
}

In this way (the top), you can take a word and generate colored letters just by calling this function.

geraLetrasColorida("Não sei, só sei que foi assim!");
    
24.12.2017 / 03:49