str_replace using arrays

Asked

Viewed 426 times

2

I want to blacken the terms searched in the results, but when I use the explode, and I try to use in str_replace, I get a 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, because if I search "new bike", returns the text, but the words are not displayed as I want.

  • Just for the record, mysql_* is (deprecated) from PHP 5.5, and functions will be removed in new versions of PHP.

  • 1

    and which command to replace?

  • The alternatives aremysqli_ functions and PDO (PHP Data Objects). Some time ago you had a very interesting question and the answers were good. (http://answall.com/questions/579/por-que-n%C3%A3o-devo-usar-fun%C3%A7%C3%B5es-do-tipo-mysql)

2 answers

3


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

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

Notice that I used the str_ireplace, so the exchange will happen regardless of the typing has been uppercase and lowercase.


If you want more performance with many results in the list, you can do so:

// 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'] );
  }
  • Good Bacco, I thought I could do it right now

2

Try it like this:

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



$title = str_replace($palavras, $palavrasnegrito, $row['texto']);

Browser other questions tagged

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