Forum Moderators: coopster

Message Too Old, No Replies

Highlight search results in php

highlight, insensitive, case, results, search

         

trex2

12:30 am on Nov 17, 2007 (gmt 0)

10+ Year Member



Hello.

I have code that highlights keywords matching in search results, but there are 2 problems:

1. It is case sensitive- I want to make it insensitive.

2. It will match and highlight other elements I don't want- such as headings/titles, and will mess up the code links. It would be great to limit the highlighting to a certain variable $row['vtext'] and nothing else.

I have read several related posts on this, but nothing I've seen quite works. Here's the current code:

if(!isset($word)) { $word = $_POST['word']; }
function callback($buffer) {
global $word;
return (ereg_replace($word, "<span class='highlight'>$word</span>", $buffer));
}
ob_start("callback");

// echo statements for results

ob_end_flush();

Any ideas? Thanks!

Habtom

5:07 am on Nov 18, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



For case-sensitivity:

When you compare the values, you can trun them both into small cases and compare (that is wherever you have put the matching condition you have):

strtolower($word) == strtolower($_POST['word']);

trex2

7:25 am on Nov 19, 2007 (gmt 0)

10+ Year Member



Hmm.. thanks, but I couldn't get that to work.

Here's what I have for the first part of my code:

$word=$HTTP_GET_VARS ['word'] ;

then this:

if(!isset($word)) { $word = $_POST['word']; }
function callback($buffer) {
global $word;
return (ereg_replace($word, "<span class='highlight'>$word</span>", $buffer));
}
ob_start("callback");
// echo statements for results
ob_end_flush();

I tried substituting this code in every possible combination I could think of, but either gave an error or behaved the same.
strtolower($word) == strtolower($_POST['word']);

any ideas?

Habtom

8:00 am on Nov 19, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sorry, my response was not on your particular scenario, should have looked a bit closer at it.

You might want to look at the case insensitive eregi_replace [php.net] to replace the ereg_replace function you have used in your code.

trex2

10:02 am on Nov 19, 2007 (gmt 0)

10+ Year Member



That did it! Great, now 1/2 of the issue is fixed. Thank you.

Habtom

11:34 am on Nov 19, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



On the same link I provided you above, there is an example to Highlight search results [php.net].