While performing a search, it’s ofter very useful to highlight in different colors, backgrounds or styles the search keywords in the results returned. This keeps focus on the keywords and helps scan the page faster to find the more relevant results.
But how exactly can that be done? As a basic idea, the following code ( a PHP class ) practically takes as parameters the text that needs to be highlighted and the particular keywords that need to stand out. Using a regular expression, every keyword in the text is replaced with a span HTML element having different styles applied according to the keyword it matches.
Please remember that the code below is just an example, it can be and should be extended; I’m only presenting it for demonstration and “how to” purposes. (more…)