Page 1 of 1

highlight some texts in a search result

Posted: Wed Aug 29, 2007 4:10 pm
by php_ghost
Hi everyone. I have created a search function for my website where I search the entire database for a user inputted keyword.

I store the results to a variable named "content" before echoing it. Now I want to highlight every character in "content" that matches the keyword. So far I have done the highlighting part but the problem is, I can't keep the case of the characters.

ex:

a keyword "php" can find the words "Php" but it won't highlight it as "Php". The "Php" becomes "php" when I use my highlighting script.

heres my code:

Code: Select all

function highlightKeywords($keyword, $contentString){
    $finalString = str_ireplace($keyword, "<span class=\"keyword-text\">$keyword</span>", $contentString);
    return $finalString;
}

echo highlightKeywords($keywordvariable, $content);
I might consider using a different approach if anyone has an Idea.

TIA

Posted: Wed Aug 29, 2007 4:19 pm
by pickle
str_ireplace(), it would appear, makes everything lowercase. Obviously you can't use str_replace() as you want to match "Php" even if the user searched for "PHP". The only thing I can think of is to use preg_replace(), which should allow you to match case-insensitively, but still allow you to keep the case in the replacement operation.

Posted: Wed Aug 29, 2007 5:23 pm
by php_ghost
hi.
I tried preg_replace() but I always get this error

preg_replace() [function.preg-replace]: Delimiter must not be alphanumeric or backslash in.

been searching google but I can't seem to find the fix for this.

Posted: Wed Aug 29, 2007 5:34 pm
by pickle
~d11wtq made a fantastic intro tutorial for regex here: viewtopic.php?t=33147

Basically, your delimiter (the first & last characters of the pattern) have to be the same character, and can't be a number, letter or \. Usually, the backslash (/) character is used.

Posted: Thu Aug 30, 2007 10:50 am
by php_ghost
thanks. i'll try that one. :wink:

Posted: Thu Aug 30, 2007 10:56 am
by John Cartwright
Make sure to include the i modifier to allow your pattern to be case insensitive.

Posted: Thu Aug 30, 2007 12:29 pm
by josa
I found this function:

http://aidanlister.com/repos/v/function ... hlight.php

It may have some useful features you can use. I can't vouch for the code quality though...

/josa