Php Text Marker An Alternative
Posted on 16 Jul 2002
by Markis Brachel (Markavian)
Rated 3.92 (Ratings: 2)
- More articles in Backend
Websites like google.com have the ability to highlight text on any page based on a search item.
Read on to learn how to highlight any text on a page using a simple PHP script.
The FunctionThe following code has come straight off the php.net online manual. The ob_start() function. Basically what it does is buffer any/all page output until you say ob_end_flush(); .. and then it outputs the whole page.
In this example a function called callback has been created, which searches through the entire output, and replaces the word 'apples' with 'oranges'. The 'callback' function is called when ob_end_flush() is initialised. e.g. ob_end_flush("callback");.
The code is like so:
It's like comparing apples to oranges.
All the output is buffered. Each time an output is detected, it is run through the callback function, which replaces all occurances of 'apples', with 'oranges'.
At the end of the script, ob_end_flush(); outputs the filtered buffer contents.
Creating Useful Code
We want to search through a document, and highlight a specified search item.
We already have a search and replace function above. To highlight a word we simply surround the text with a <span class="highlight"> tag.
Firstly we need to set up the CSS class:
- background: #44AA44
Next the code is altered to search for a specified search criteria, and when found. surround this text with the <span class="highlight"> tag.
For the 'callback' function to work
$searchItemmust be set.
NB: The line:
global $searchItem;- . If you don't know, please see PHP variable scope for details.
The altered code follows:
It's like comparing bannanas to oranges to apples to peaches.
Now if you send $searchItem=oranges to the script, the word 'oranges' will be highlighted.
If you've got PHP, go on.. try it!
Extending the script
Thats the basic principle.. however, you may like to do a improved matching filter, e.g. oranges aren't the same as Oranges.. and maybe the user would prefer orange and Orange and Oranges to be highlighted.
Also, theres a small snag, if someone searches for 'p', it messes up the code a tad.
Please try out the script, and comment on any successes / added features below. If you can think of any faster / better ways of doing this search / replace then please post.
And for your reference:
www.php.net - Still the best source for PHP documentation.
PHP Function ob_start() - The all important 'buffer output' command.
PHP variable scope - A useful page about variable scope, variables inside functions, and things which aren't obvious to the newer programmer.