6.6. Highlighting the Search Term
Problem
You want to make it clear to site visitors what they searched for when they view a results page.
Solution
Combine a stylesheet rule with a PHP text-processing function to make the search term stand out.
For this Recipe, let's assume you have a search form that queries a database for articles, like this:
<form action="/search/search.php" method="post"> <input name="arg" type="text" value="" size="10" maxlength="20"> <input type="submit" value="Go"> </form>
The value of the <input>
field arg
gets passed to the
search.php script and becomes the variable
$arg
. First, add a rule to your
stylesheet that will highlight this block of text, as shown in Figure 6-3:
.arg { background-color: #00CCCC; font-weight: bold; }
Then add a line to the results page that simply prints the search term, wrapped in the style:
Figure 6-3. Highlighting the search term on the results page confirms for visitors that they got what they requested
echo "You searched for <span class=\"arg\">".$arg." </span>";
You also can create a custom PHP function (or modify one you've already made to handle other text-processing tasks) to highlight the search term in the body of the article that the visitor requests from the results page:
function processText($text,$arg) {
…other text-processing commands
…
$text = str_replace($arg,"<span class=\"arg\">".$arg."</span>",$text);
return $text;
}
Get Web Site Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.