Skip to main content
Inspiring
August 29, 2006
Answered

Highlighting search terms in quotes

  • August 29, 2006
  • 1 reply
  • 348 views
Hope someone can help with this - I have a function that I'm using to highlight search terms in the results page :



<?php function highlightResult($keyword,$result) {
if (get_magic_quotes_gpc()) {
$replace = stripslashes($keyword);
}
else {
$replace = $keyword;
}
$replaceArr = explode(" ",$replace);
for ( $i = 0; $i < sizeof($replaceArr); $i++ ) {
$result = preg_replace("/{$replaceArr[$i]}/i","<b><font color=#FF0000>{$replaceArr[$i]}</font></b>",$result);
}
$highlighted = $result;
return $highlighted;
}
?>

Basically the search code I'm using uses inverted commas to group individual words as a phrase.
eg

If you search on : technical knowledge

It will return any results that contain technical OR knowledge. (and are highlighted correctly)

If you search on : technical, knowledge

It will return any results that contain technical AND knowledge. (and are highlighted correctly)

If you search on : "technical knowledge"

It will return any results that contain the exact phrase technical knowledge - and in this case although the results are correct, the phrase isn't highlighting.

I presume when it comes to highlighting instead of reading technical knowledge its reading "technical knowledge", in which case it's not highlighting at its not a matching phrase because of the inverted commas, so what I need is to somehow break the phrase so that it remove the inverted commas and make it read the words or phrase inside...

If anyone could help amend the code above to do this that would be hugely appreciated.

Cheers,
Iain
This topic has been closed for replies.
Correct answer johngordon12
If it ever comes in handy for anyone else, the code that did it was :

<?php function highlightResult($keyword,$result) {
if (get_magic_quotes_gpc()) {
$replace = stripslashes($keyword);
}
else {
$replace = $keyword;
}
$replace = preg_replace("/\"|\,/i","",$replace);
$replace = preg_replace("/ {2,}/i"," ",$replace);
$replaceArr = explode(" ",$replace);
for ( $i = 0; $i < sizeof($replaceArr); $i++ ) {
$result = preg_replace("/{$replaceArr[$i]}/i","<b>{$replaceArr[$i]}</b>",$result);
}
$highlighted = $result;
return $highlighted;
}
?>

1 reply

johngordon12AuthorCorrect answer
Inspiring
August 30, 2006
If it ever comes in handy for anyone else, the code that did it was :

<?php function highlightResult($keyword,$result) {
if (get_magic_quotes_gpc()) {
$replace = stripslashes($keyword);
}
else {
$replace = $keyword;
}
$replace = preg_replace("/\"|\,/i","",$replace);
$replace = preg_replace("/ {2,}/i"," ",$replace);
$replaceArr = explode(" ",$replace);
for ( $i = 0; $i < sizeof($replaceArr); $i++ ) {
$result = preg_replace("/{$replaceArr[$i]}/i","<b>{$replaceArr[$i]}</b>",$result);
}
$highlighted = $result;
return $highlighted;
}
?>