Page 1 of 1

Highlighting search keywords

Posted: Wed Aug 11, 2004 5:18 am
by anjanesh
Im trying to highlight search keywords but str_replace is case sensitive
$row['Info'] contains "Park" and on searching park I want it to return this too. But I want the text display exactly as it was in the db,

Code: Select all

$row['Info']=str_replace($_GET['search'],'<FONT COLOR=#555555>'.$_GET['search'].'</FONT>',strtolower($row['Info']));
ends up highlighting it but as park and not Park which is the original text in the db.
Any idea how to overcome this ?
Thanks

Posted: Wed Aug 11, 2004 6:28 am
by JayBird
try str_ireplace() which a the case INSENSITIVE version of str_replace()

http://se.php.net/manual/en/function.str-ireplace.php

Mark

Posted: Wed Aug 11, 2004 11:27 am
by feyd
str_ireplace is php5 only.. so you may want to use a regex..

Posted: Wed Aug 11, 2004 12:18 pm
by anjanesh
I think eregi_replace is the solution for this

Posted: Wed Aug 11, 2004 12:30 pm
by anjanesh

Code: Select all

$row&#1111;'Info']=eregi_replace($_GET&#1111;'search'],'<FONT COLOR=#555555>'.$_GET&#1111;'search'].'</FONT>',$row&#1111;'Info']);
still replaces the uppercase to lower in the replacement part.
I searched for park and there were 2 results. One has 'park' while the other has 'Park'. Obviously both must show up. But when displaying back for highlighting they should contain the original text - 'park' and 'Park'. But 'Park' gets converted to 'park'

Posted: Wed Aug 11, 2004 12:41 pm
by feyd
that's because you're replacing with the search string.. try this instead:

Code: Select all

$row['Info']=preg_replace('#'.preg_quote($_GET['search'],'#').'#i','<FONT COLOR=#555555>\\0</FONT>',$row['Info']);

Posted: Wed Aug 11, 2004 12:56 pm
by anjanesh
Thanks feyd.
I've to read preg fns. Was working on ereg instead.

Posted: Wed Aug 11, 2004 12:59 pm
by feyd
the ereg_* functions work nearly the same, I just prefer using the preg functions, as most of the controls are all in the regex string, instead of a mix between there and the function name and other things..

Posted: Wed Aug 11, 2004 1:34 pm
by m3mn0n
Another solution is [php_man]strtolower[/php_man]()

So all comparison can be in lowercase.

Posted: Wed Aug 11, 2004 1:41 pm
by feyd
he was already using strtolower in his original post, and as he said, it didn't work the way he'd like it.. and I'd have to agree and the use of strtolower is nearly useless, because of the added work you'll need to do to get the original text to be highlighted, instead of it being replaces entirely by lowercased text.. :?

Posted: Wed Aug 11, 2004 1:43 pm
by m3mn0n
/me needs to read more careful

/me also needs more coffee


/me runs away now