views:

145

answers:

2

I'm working on a simple search engine for a newspaper application. When the user types a keyword, a results page is shown, highlighting the term with a color.

I'm currently doing this:

$title = str_ireplace($term, "<span class='highlight'>$term</span>", $note->Title);

Great, str_ireplace() makes the case-insensitive search, but when the case doesn't match the note (i.e. the user looks for "MONEY" and the note says "money"), this happens:

malvinas | Resultados de la búsqueda

   1. malvinas: Argentina va a la ONU y Londres se enfurece » en Actualidad  
      [...] Naciones Unidas, Ban-Ki Moon, ante quien reiterará que se cumplan las
resoluciones de la ONU sobre el tema de la soberanía de las Islas [...] 

The original title of the note is "Malvinas: Argentina va a la ONU y Londres se enfurece" (not "malvinas: ", etc.)

How can I do a highlight without changing the original word's CaSe?

+1  A: 

You should use backreferences, with a case-insensitive modifier. That way when you replace the word, you are replacing it with itself (maintaining its case) and not replacing it with whatever the casing was that was used in the search.

Using this method with preg_replace will allow you to pass an array of search terms in, and a generic replacement-pattern for each.

Jonathan Sampson
+1  A: 

Use regex:

$term = 'hello';
$str = 'Hello there';
$term_escaped = preg_quote($term);
$out = preg_replace("~$term_escaped~i", '<b>\0</b>', $str);

echo $out;

Output:

<b>Hello</b> there
Max Shawabkeh
This worked perfectly. Thanks a lot!
Joel Alejandro