Echo colored in php

Asked

Viewed 960 times

1

Can I leave ECHO in PHP colored ? Print in HTML, letter by letter colored ex:

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

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

All that der LIVE and DEAD (printed on screen) come out all colored

2 answers

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>";
    }
}

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

geraLetrasColorida("Não sei, só sei que foi assim!");

1


Use str_split, explode or even iterate string will not work if it happens to be using Unicode (UTF-8 for example), as explained in:

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

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

I used this answer as a basis https://stackoverflow.com/a/25996226/1518921 to generate colors, it should be something like:

<?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 so:

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.

Browser other questions tagged

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