Highlight word in search with php

Asked

Viewed 318 times

-1

I am trying to highlight a certain word in the search as follows:

The user types the word in the search stand out and this 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;
  • Note that you are using echo $texto, instead of echo $tarjado.

2 answers

1


You can use the str_replace, normally:

<?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;
  • How careless of me. You’re right Inkeliz, I was giving an echo in the wrong variable.

  • Thank you Inkeliz.

  • 1

    Tip: use the tag <mark>, because it increases the semantics of the page.

0

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

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

Exit:

...consectetur stand out adipiscing Elit, sed do eiusmod tempor...

Browser other questions tagged

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