php highlight search keywords [working solution]! I just spent the whole night writing this little script for my search engine. Now i want to improve it.

Any ideas?

&lt;?php 
echo "KEYWORDS : ".  $searchstring  = "the and";

$sentence = "Skype Home is unavailable at the moment. Check back later to see your news and alerts.  It's easy to start a conversation on Skype:  Choose a contact and start talking Call a phone or mobile from the dial pad, or send an SMS.";

echo "&lt;br&gt;&lt;br&gt;&lt;b&gt;ORIGINAL STRING&lt;/b&gt;&lt;br&gt;&lt;br&gt;$sentence";


$kt=split(' ',$searchstring); //Breaking the string to array of words

$num=1;

while(list($key,$val)=each($kt)){
    // do not load sentence from session on first run!  

    if($num&lt;=1){
    } else {
        $sentence  = $_SESSION['NewSentence'];
    }
    if($val&lt;&gt;" " and strlen($val) &gt; 0){

        // make keyword bold and send entire sentence to session

        $_SESSION['NewSentence']    = eregi_replace ("$val", "&lt;b&gt;$val&lt;/b&gt;", $sentence);
        // output sentence with added keyword

        echo "&lt;br&gt;&lt;br&gt;$num bolding:  &lt;b style='color:green;'&gt;$val&lt;/b&gt; &lt;br&gt;&lt;br&gt;  ".$_SESSION['NewSentence'];

        $num++;
    }
}

// make all bold keywords to red`

echo '&lt;br&gt;&lt;br&gt;&lt;b&gt;FINAL STRING&lt;/b&gt;&lt;br&gt;&lt;br&gt;';
echo  $_SESSION['NewSentence'] = eregi_replace ("&lt;b&gt;", "&lt;b style='color:red'&gt;", $_SESSION['NewSentence']);

//destroy  session
unset($_SESSION['NewSentence']);
session_unregister($_SESSION['NewSentence']);?&gt;
Use of deprecated functions

Both split() and eregi_replace() are deprecated since PHP 5.3. Don't use them.

Use preg_replace() instead of eregi_replace() and explode() instead of split() Other alternatives are str_replace() and preg_split().

Unexpected results

When the search string is lowercase, all replaced words will be lowercase too. The case of the original word is not preserved.

Unused variables

The $key variable is assigned but never used. In fact, the entire while loop is odd. Use a foreach loop instead, like so:

foreach($kt as $val) {
    ...


Missing function

The code should be in a function. The function would require two parameters, the string and an array of words to highlight, and return the result string. The function should not echo anything (but I presume the echo statements are debugging things).

Old HTML

Although valid, the use of &lt;b&gt; tags is outdated. It describes formatting in a document layout, without specifying the need for the format. You should use html for layout and css for styling. Then you can replace the &lt;b&gt; with a &lt;span class="highlight&gt; (or any other sensible class name).