problema com função para estilizar palavras chave em consulta
A função é para pegar uma string ($text) e marcar as palavras pesquisadas ($words) com css ($colors), mas não consigo fazê-la funcionar quando a string ($text) contém caracteres especiais, barras etc.
O $text está vindo da base de dados e contém entidades html(ex: á Õ) datas etc.
function highlightWords ( $text , $words , $colors = null )
{
if( is_null ( $colors ) || ! is_array ( $colors ))
{
$colors = array( 'azul' , 'laranja' , 'verde' );
}
$i = 0 ;/ the maximum key number /
$num_colors = max ( array_keys ( $colors ));
/ loop of the array of words /
foreach ( $words as $word )
{
/ quote the text for regex /
$word = preg_quote ( $word );
/ highlight the words /
$text = preg_replace ( "/\b($word)\b/i" , '<span class="highlight_' . $colors [ $i ]. '">\1</span>' , $text );
if( $i == $num_colors ){ $i = 0 ; } else { $i ++; }
}
/*** return the text ***/
return $text ;
}Discussão (1)
Carregando comentários...