tags:

views:

41

answers:

2

Hello,

The function below puts a search term $find in bold. It works just fine. However, I would like to make it so that instead of putting $find in bold, it gives it a yellow background, as in the CSS property background-color:#FFFF00;. How could I do this?

Thanks in advance,

John

The function:

function highlight($text, $words) {
    preg_match_all('~\w+~', $words, $m);
    if(!$m)
        return $text;
    $re = '~\\b(' . implode('|', $m[0]) . ')\\b~i';
    return preg_replace($re, '<b>$0</b>', $text);
}

The PHP/HTML:

echo '<td class="sitename1search"><a href="http://www...com&gt;'.highlight($row["title"], $find)).'</a></td>';

The CSS:

.sitename1search { width: 800px;
            font-family: Arial, Helvetica, sans-serif;
            font-weight: normal;
            font-size: 12px;
            overflow:hidden !important;
            color: #000000;
            padding-bottom: 0px;

}

.sitename1search a{ width: 350px;
            font-family: Arial, Helvetica, sans-serif;
            font-weight: normal;
            font-size: 12px;
            overflow:hidden !important;
            color: #004284;
            padding-bottom: 0px;

}
+4  A: 

Replace

return preg_replace($re, '<b>$0</b>', $text);

With

return preg_replace($re, '<span style="background-color:#FFFF00;">$0</span>', $text);
Jonah Bron
+4  A: 

Just add the class attribute in your PHP:

function highlight($text, $words) {

    // your php code
    return preg_replace($re, '<span class="found-term">$0</span>', $text); // changed line
}

and add this to your CSS file:

.found-term { 
  background-color:#FFFF00;
  font-weight: bold; 
}

It's better than style attributte in PHP - simply because clashing of logic and design is mostly bad idea.

MartyIX
+1. This one is slightly better, as it keeps HTML and CSS seperate (which is always best practice).
Jonah Bron
+1: I'd just update your answer so your b's class "founded-term" matches the css "found-term". Also, a span is probably more semantically correct here.
sdolan
@sdolan: Thanks for noticing that! I've update the code.
MartyIX