Change part color of a string

Asked

Viewed 1,102 times

2

I need to do a query in Mysql and change the cvor of a piece of text if a specific string is contained in the text.

For example: My tah td returns a text

<td id="conteudo" class="tablesaw-priority-5 tablesaw-cell-visible>{{$value->conteudo}}</td> 

If this returned text has any substring for example: XXXX

I need this XXXX to be in red and the rest in the original color in black.

It is possible to accomplish this?

  • The substring that needs to change color is default, that is, it will always be the same text?

  • No @Andre text changes according to the SELECT output in the database. But the color can always be the same.

  • And words that have the term should also be highlighted? For example, when searching for "typed", the word "constipated" should be highlighted as having "typed"?

  • not necessary, only the same code.

  • you are using some framework or template engine? (Blade, Twig...)

  • @Lorena But the code changes depending on the answer.

  • This is done in PHP or Javascript?

Show 2 more comments

2 answers

5

in the template engine you can use any function available on PHP, knowing this we can use the function preg_replace replacing a text according to a regular expression, see:

$texto = "este é o texto-que-eu-quero"
$formatado = preg_replace("/texto-que-eu-quero/", "<span>xxx</span>", $texto);
echo $formatado; // A saída será "este é o <span>xxx</span>"

Your code:

<td
    id="conteudo"
    class="tablesaw-priority-5 tablesaw-cell-visible>
        {{ preg_replace("texto-que-eu-quero", "<span>xxx</span>", $value->conteudo) }}
</td>

This way you can apply a css only in span and could use anywhere. (don’t forget to apply a class in span to avoid conflicts)

span {
    color: yellow;
}
  • 3

    Curiosity: could use the tag <mark> that already highlights the text by default and leaves the semantic content.

4


Follow an example of changing part of a string.

var valor = "Aqui vem o resultado da sua string";
var termo = "resultado";

var str = valor.replace(termo, "<span class='AlteraCor'>" + termo + "</span>")

document.getElementById('result').innerHTML = str;
.AlteraCor{
color: blue;
}
<span id="result"></span>

  • Could I change the color of the text that is within two specific characters? Ex: between characters # and : Ex #Hello World: Leaving Hello World with another color.

Browser other questions tagged

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