Highlight word in search with php

-1

I'm trying to highlight a particular word in the search as follows:

The user types in the search the word highlight and that word would be highlighted in the text. For this, I tried with the 02 codes below, but I could not:

First code:

$buscar = "destacar";
$texto = "Lorem ipsum dolor sit amet, consectetur destacar adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";

$tarjado = preg_replace("/($buscar)/i", "<span style='background-color:#FF0;color:#F00'>\1</span>", $texto);
echo $texto;

Second code:

$buscar = "destacar";
$texto = "Lorem ipsum dolor sit amet, consectetur destacar adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";

$tarjado = preg_replace( sprintf( '/\b(%s)\b/i', is_array( $buscar ) ? implode( '|', $buscar ) : $buscar ), '<span class="font-weight: bold">$1</span>', $texto );
echo $texto;
    
asked by anonymous 28.05.2018 / 15:24

2 answers

1

You can use str_replace , typically:

<?php

$buscar = "destacar";
$texto = "Lorem ipsum dolor sit amet, consectetur destacar adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";

$texto = str_replace($buscar, '<mark>'.$buscar.'</mark>', $texto);
echo $texto;
    
28.05.2018 / 15:39
0

Just to reinforce here in the post, if you have a very large text and just want to highlight a portion of this text with the highlighted word, you can do this:

$buscar = "destacar";
$texto = "Lorem ipsum dolor sit amet, consectetur destacar adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";

$trecho = preg_match_all ("/([\P{Cc}]{0,45}){$buscar}([\P{Cc}]{0,45})/i", $texto, $testar);

foreach($testar[0] as $teste){
        $tarjado = preg_replace("/($buscar)/i", "<span style='font-weight: bold'>\1</span>", $teste);
        echo  "...".$tarjado."...";
}

Output:

... consectetur adipiscing elit, sed of eiusmod tempor ...

    
28.05.2018 / 15:51