Intended audience
Background
Getting results from a database
Highlighting search criteria
Getting a search result synopsis
Conclusion
About the author
Intended audience
The purpose of this article is to show how to build two
functions that help make search results from a database look more appealing to
users.
Background
Most people are familiar with doing searches on Google, and
how Google formats search results. First, the search criteria text appears in a
bold font. Second, the text of the search results ends with an ellipsis (…)
to let the user know that there is more information where that came from. These
little UI features make it easy for readers to find what they are looking
for.
Getting results from a database
There’s no doubt that one of PHP’s strongest features is its
ability to interact with various databases. For this article we will be using
MySQL but the code presented here can be modified to support other databases
with little effort.
By way of a primer, here’s a sample script that you could use
to query a database:
<?php
$query = "
SELECT id, title, author, body
FROM article
WHERE author='John Doe'
";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$body = $row['body'];
?>
Highlighting search criteria
On of the handy things many web sites do with their search
results is highlight in some way the search criteria in the search results. As
mentioned before, Google does this by making the search criteria text bold as
seen in the following example:

In our example we will change the background color of the
text.
Highlighting text involves changing the style of the text
using the CSS ‘background-color’ property. This can easily be done using the
style parameter of many tags. In this case we’ll use the <span>
tag:
<span style="background-color: Yellow;">this is some sample text.</span>
Obviously we need to be able to dynamically change the
background color using PHP:
<span style="background-color: <?php echo $bgcolor; ?>">this is some sample text.</span>
We will get the value of
$bgcolor later in the
article.
So now, how do we put our search criteria in between the
<span> tags? One way is to store the start and end tags in their own PHP
variables. Then we can concatenate everything together using PHP’s
concatenation operator.
<?php
$start_tag = "<span style='background-color: $bgcolor '>";
$end_tag = '</span>';
$highlighted_results = $start_tag . $criteria . $end_tag;
?>
Next we need some way to highlight the criteria only, without
highlighting the rest of the result text. The best and most portable way to
make any changes to the search results is by using a function.
<?php
function highlight_search_criteria($search_criteria, $bgcolor='Yellow')
{
$start_tag = "<span style=' background-color: $bgcolor'>";
$end_tag = '</span>';
$highlighted_results = $start_tag . $search_criteria . $end_tag;
return $highlighted_results;
}
?>
This function takes as its parameters the search criteria text
and an optional background color. Here’s an example of how you might use this
function:
<?php
$highlighted_criteria = highlight_search_criteria('John Doe');
echo $highlighted_criteria;
?>
This would produce the following text:
John Doe
Notice that we left out the second parameter of the function.
Since the second parameter is defined with a default value, it can be left blank
and the default value will be used. If you wanted to change the background
color, from Yellow to Green for example, you would provide ‘Green’ as the second
parameter when calling the function.
Now all this is nice and it does the job, but we can take it
even further. Wouldn’t it be nice if we could provide the complete text as well
as the search criteria and have the criteria automatically highlighted inline?
With a little more work to our function we can do just that.
<?php
function highlight_search_criteria($search_results, $search_criteria, $bgcolor='Yellow')
{
$start_tag = ';';
$highlighted_results = $start_tag . $search_criteria . $end_tag;
return eregi_replace($search_criteria, $highlighted_results, $search_results);
}
?>
This function adds the full search results text as the first
parameter. Then, using the
eregi_replace()
function built-in to PHP, we can replace all occurrences of
$search_criteria throughout
$search_results with
$highlighted_results.
Our function is nearly complete but we still have one last
thing to do. What would happen if the search criteria are not found anywhere in
the search results? You might find some unexpected things happen if you replace
nothing with something throughout your search results. Because of this, we need
to check that we actually have search criteria to highlight inside our
function.
<?php
function highlight_search_criteria($search_results, $search_criteria, $bgcolor='Yellow')
{
if (empty($criteria)) {
return $search_results;
} else {
$start_tag = '<span style='background-color: $bgcolor'>';
$end_tag = '</span>';
$highlighted_results = $start_tag . $search_criteria . $end_tag;
return eregi_replace($search_criteria, $highlighted_results, $search_results);
}
}
?>
And here’s an example of how to use the function:
<?php
$db_result_text = "The users with the most points in this game were John Doe,
Jane Smith, and Bill Bobbins.";
$result_text = highlight_search_criteria($db_result_text, 'John Doe');
echo $db_result_text;
?>
This results in:
The users with the most points in this game were John Doe,
Jane Smith, and Bill Bobbins.
There are a few more things you could do to this function.
For example, you could provide the option of either highlighting the background
color or making the criteria bold. You might even extend it so that it
automatically picks a random background color each time it is used. I’m sure
you’ll think of a million other features to add to this function that will make
it even more useful.
Getting a search result synopsis
As a companion to the
highlight_search_criteria()function we
built above, the following function can allow you to easily summarize your
search results.
When you are listing several results you probably don’t want
to display the full results, because your users might end up with a annoyingly
long pages that require a lot of scrolling.
The most common way to “summarize” text (which is
not really “summarizing” but simply “truncating”) is to
quote the first few words followed by an ellipsis. An example of this might
be:
We hold these truths to be self-evident…
In order to do this we need to reduce the text from a variable
number of words to a manageable number, say 10. We’ll use the
explode() function
to do this.
explode() takes a
string and breaks it up into an array using a specified delimiter. This is
preferable over using a regular expression, as it scales better and doesn’t look
like a rash of cartoon profanity. Here is what explode() looks like in
action.
<?php
$text_array = explode(' ', 'This is just a test');
print_r($expl_array);
?>
In this example we are splitting the string “This is just a
test.” using the space character as a delimiter. Here is the output of the
script.
Array
(
[0] => This
[1] => is
[2] => just
[3] => a
[4] => test
)
Now that we have all the words of our result text inside an
array we can easily get the first 10 words. This is how it looks in the
function:
<?php
function summarize_search_result($result_text, $num_words=10) {
$text_array = explode(' ', $result_text, $num_words + 1);
return implode(' ', array_slice($text_array, 0, $num_words). '...';
}
?>
Here we have a function that accepts the result text as its
first parameter as well as an option integer representing the number of words in
the summary. In the function we first get the array of words using
explode() up to the desired number of
words (third parameter to explode()).
Finally, we use the
implode() function to bring the words
back together, and append the ellipsis to the result.
Here’s an example of how to use it:
<?php
$some_text = "WHEN in the Course of human Events, it becomes necessary for
one People to dissolve the political bands which have connected them with another
, and to assume among the Powers of the Earth, the separate and equal Station to
which the Laws of Nature and Nature's God entitle them, a decent Respect to the Opinions
of Mankind requires that they should declare the causes which impel them to the Separation.";
$summary_text = summarize_search_result($some_text, 15);
echo $summary_text;
?>
This results in:
WHEN in the Course of human Events, it
becomes necessary for one People to dissolve…
As with
highlight_search_criteria() you can
probably find many more ways to extend this function.
Conclusion
Using these two functions together you can get results very
similar to Google Groups where the search criteria is not only bold but is highlighted.
<?php
$some_text = "WHEN in the Course of human Events, it becomes necessary for
one People to dissolve the political bands which have connected them with another,
and to assume among the Powers of the Earth, the separate and equal Station to which
the Laws of Nature and Nature's God entitle them, a decent Respect to the Opinions of
Mankind requires that they should declare the causes which impel them to the Separation.";
$searched = highlight_search_criteria($some_text, 'Events');
$summarized = summarize_search_result($searched, 15);
echo $summarized;
?>
This will give you:
WHEN in the Course of human Events, it becomes necessary for
one People to dissolve…
The functions covered here are far from complex or advanced
PHP but I think you will agree that they are very handy functions to have in any
web developer’s toolkit. They also do a great job of showing off the power of
PHP!
About the author
Darrell Brogdon is an independent consultant
specializing in Web Application development. He can be reached at darrell@brogdon.net.


One comment to “Googlifying Search Results”
August 18th, 2009 at 2:59 pm
Great tutorial, well expained I find it usefull
<a href="http://www.acerlaptops.info">Acer laptops</a>