Forum Moderators: coopster
I have a search form which makes queries to a database. In the form the user can search for many words (word1 && word2 && word3). I want in the results to highlight the words that the user has searched for. I 've searched in the internet and i've found some codes but none of them works with all the possible results.
What I have found so far which is closer to what I want is the following:
I create the appropriate array:
$highlight2=array(james=>yellow, span=>red,....);
I put this order in the field where the words must exist:
print(search_highlight($highlight2,$row[$i]));
and the function is:
function search_highlight($needle, $haystack)
{
foreach($needle as $key=>$val)
{
$haystack= preg_replace("/($key)/i", '<span style="background-color:'.$val.'">\\0</span>', $haystack);
}
return $haystack;
}
The problem is that when the first word is found and highlighted, the searching for the second word begins. If the second word is for example "style" it will change the word in the tag, so it is gonna become a mess!
Does anyone knows how it can ignore the tags and if possible not to be compulsory to find a word of the array?
Any advise will be invaluable. Thank you in advance
$key1 = wflkjWEFkljffce;
$key2 = wqweewqopilklkq;
$key3 = oiuevfrlklmcwpw;
Then do a search and replace with those keys. After all the highlighted words have been found you can do another search and replace, replacing the keys with html tags.
I hope there is a better solution though.
I also found this code in the the php manual which should do the job much better. It processes only the parts of the text outside of markup tags. Nice.
<?php
function hilites($search, $txt) {
$r = preg_split('((>)¦(<))', $txt, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = 0; $i < count($r); $i++) {
if ($r[$i] == "<") {
$i++; continue;
}
$r[$i] = preg_replace(
"/($search)/i", "<span class='hilite'>\\1</span>", $r[$i]
);
}
return join("", $r);
}
?>
[edited by: jatar_k at 5:46 pm (utc) on July 20, 2004]
[edit reason] disabled smiles [/edit]