str_replace using arrays

1

I want to negate the searched terms in the results, but when I use explode , and I try to use str_replace , I get an array back.

<?php
$search_term = filter_var( $_GET['s'], FILTER_SANITIZE_STRING );

$palavras = explode( ' ', $search_term );

$q = 'SELECT * FROM classificados WHERE';
for ( $i = 0; $i < count($palavras); $i++ ) {
  $q.= " texto LIKE '%" . $palavras[$i] . "%' AND " ;
}
$q.= " aprovado='s' ORDER BY ID desc";

$r = mysql_query( $q );
if ( mysql_num_rows( $r )==0) //no result found
{
  echo "<div id='search-status'>Nenhum resultado encontrado!</div>";
}
else //result found
{
  echo "<ul>";

  while($row = mysql_fetch_assoc($r)) {
  // aqui nao funciona
  $title = str_replace($palavras, "<b>". $palavras[$i] ."</b>", $row['texto']);
?>

The search works, so if I look for "new bike", it returns the text, but the words do not appear as I want.

    
asked by anonymous 10.10.2014 / 19:03

2 answers

2

The problem is that to use str_replace in this way, you would need two arrays , one with normal words, and one with words already in bold. Better would be a loop:

$title =  $row['texto'];
foreach( $palavras as $palavra ) {
    $title = str_ireplace( $palavra, '<b>' . $palavra . '</b>', $title );
}

Note that I have used str_ireplace , so the exchange will happen regardless of whether the typing has been case sensitive.


If you want higher performance with lots of results in the listing, you can do this:

// acrescentar no topo
$palavras = explode( ' ', $search_term );
$negritos = $palavras;
array_walk( $negritos, function( &$neg ) { $neg = '<b>'.$neg.'</b>' } );

// e na parte do loop:
  echo "<ul>";
  while( $row = mysql_fetch_assoc($r) ) {
     $title = str_ireplace( $palavras, $negritos, $row['texto'] );
  }
    
10.10.2014 / 19:21
1

Try this:

$palavras = explode( ' ', $search_term );
$palavrasnegrito = array();
foreach ($palavras as $p)
   $palavrasnegrito[] = "<strong>{$p}</strong>";



$title = str_replace($palavras, $palavrasnegrito, $row['texto']);
    
10.10.2014 / 19:24