Hi,
I was making a search box and was trying to highlight the words that the users will enter in the search box,for example if the user enter "kids" in the searchbox it should highlight the "kids" word in the result............. is anyone have an idea how to do that

Dani AI

Generated

Brief, practical guide to reliable search-term highlighting.

This thread raised the classic pitfalls: is right that matching text is needed, and correctly warns that naive regex replaces will corrupt HTML. demonstrates a server-side approach, but modern practice avoids deprecated functions and inline <font> tags. Two safe patterns work best: a DOM-aware client-side highlighter for already-rendered pages, or server-side snippet generation for search-result summaries (with careful escaping).

A compact, robust client-side strategy is to walk text nodes and wrap matches in a semantic element such as <mark class="search-term">. The example below shows the core idea: escape the user term for regex safety, collect text nodes with a TreeWalker, skip script/style/code blocks, and replace only the matched text with a <mark> element.

function escapeRegExp(s) {
  return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function removeHighlights(root) {
  root.querySelectorAll('mark.search-term').forEach(m => m.replaceWith(document.createTextNode(m.textContent)));
}

function highlight(root, term) {
  if (!term || !term.trim()) return;
  const regex = new RegExp('\\b' + escapeRegExp(term) + '\\b', 'giu');
  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false);
  const nodes = [];
  let n;
  while ((n = walker.nextNode())) nodes.push(n);
  nodes.forEach(textNode => {
    const parent = textNode.parentNode;
    if (!parent || parent.closest('script,style,pre,code')) return;
    const text = textNode.nodeValue;
    let last = 0;
    const frag = document.createDocumentFragment();
    regex.lastIndex = 0;
    let m;
    while ((m = regex.exec(text)) !== null) {
      if (m.index > last) frag.appendChild(document.createTextNode(text.slice(last, m.index)));
      const mark = document.createElement('mark');
      mark.className = 'search-term';
      mark.textContent = m[0];
      frag.appendChild(mark);
      last = regex.lastIndex;
      if (regex.lastIndex === m.index) regex.lastIndex++;
    }
    if (last < text.length) frag.appendChild(document.createTextNode(text.slice(last)));
    if (frag.childNodes.length) parent.replaceChild(frag, textNode);
  });
}

Server-side notes and quick tips: generate short snippets (e.g., ~150 chars) around the first match and escape HTML before inserting highlight tags to prevent XSS. Avoid attempting to regex-replace across raw HTML; use HTML-escaping or a parser. Always handle case/word boundaries and Unicode (tokenization or language-aware stemming if needed). Clear previous highlights before reapplying, skip code/style blocks, use CSS for visible contrast (do not rely on color alone), and prefer <mark> for semantics and accessibility.

Recommended Answers

All 5 Replies

You will need some sort of regular expression to find the matching word.
E.g:

$i=0;
while (there are results)
{
    if(preg_match("/the search term/i", $results[$i], $yellow))
    {
           echo "<span id = "yellow">" $yellow[$i] . $results[$i] ."</span><br>";
    }
}

Not exactly... but you can follow the logic x

Member Avatar for Member #720405

Hi micahgeorge,

I've done this before in a previous project. However I didn't use PHP, rather JS. Once the user entered the search term, the term was submitted to a PHP script that displayed the search results. Each of the search result URLs were appended with ?query=<search-term>. I then placed JS (there are pre-existing scripts and I didn't want to rewrite the wheel) code on the page to check for the ?query=<search-term> and highlight the search term if it was found.

I used a jQuery plugin to highlight the words on the page.

Cheers,

James

Member Avatar for Member #720405

Using a regular expression is a valid way of highlighting words too. However it gets quite difficult to write one that doesn't affect the page's HTML. You pretty much end up having to write a HTML parser so you don't muck up the HTML. In my previous project I started writing my own regular expression but moved to a pre-built solution after noticing how the regular expression caused formatting errors on a few pages.

Consider trying to highlight the term "bug".

<p class="bug-paragraph">This paragraph is about bugs...</p>

And consider the broken result of nonshatter's regular expression (I know that he has oversimplified it however consider how difficult it is to write a regular expression that highlights all instances and doesn't destroy HTML- try highlighting "class", "p", HTML entities (e.g. ate => &#38;#65;te etc).

<p class="<span class="search-term">bug</span>-paragraph">This paragraph is about <span class="search-term">bug</span>s...</p>

You will need some sort of regular expression to find the matching word.
E.g:

$i=0;
while (there are results)
{
    if(preg_match("/the search term/i", $results[$i], $yellow))
    {
           echo "<span id = "yellow">" $yellow[$i] . $results[$i] ."</span><br>";
    }
}

Not exactly... but you can follow the logic x

Hi nonshatter,
Thanks for ur reply but I am a beginner will you please explain ur code.... I tried this but not getting....

go through this

<? 
ob_start();

extract($_REQUEST); 
extract($_POST);

$searchtext=$_REQUEST['searchtext'];/////////////$_REQUEST['searchtext'] your search content
if($searchtext=='')
{
$exists=1;
}
function search_highlight($needle, $replace, $haystack)
{
 $haystack = eregi_replace($needle,$replace,$haystack);
 return $haystack;
}
//echo $searchtext;exit;
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
 <?
       if($searchtext!='')
       {
        $selectstatic=mysql_query("select * from static_pages where description like '%$searchtext%'");
         $count=mysql_num_rows($selectstatic);
         if($count>0)
         {
         ?>
         <p  class="blue_hrd">Search Content "<?=$searchtext?>"</p>
         <?
        
while($fetchstatic=mysql_fetch_array($selectstatic))
{
         ?>
        <div style="width:850px; float:left; margin:0px; padding:0px;">
         <p class="normal_text"><span class="blue_textt"><strong><?=$fetchstatic['name']?></strong></span><br />
         <? echo search_highlight($searchtext, "<b><font style='color:white; background-color:grey;'>" . $searchtext . "</font></b>", $fetchstatic['description']);?>
         </p>
         </div>
          <?
         }
         }
        }
         ?>
</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.