views:

45

answers:

3

I want want my output like this when I search a keyword like

"programming"

php programming language

How to do this in php mysql?

Any idea?

+1  A: 

Just perform a str_replace on the returned text.

$search = 'programming';
// $dbContent = the response from the database

$dbContent = str_replace( $search , '<b>'.$search.'</b>' , $dbContent );

echo $dbContent;

Any instance of "programming", even if as part of a larger word, will be wrapped in <b> tags.

For instances where more than one word are used

$search = 'programming something another';
// $dbContent = the response from the database

$search = explode( ' ' , $search );
function wrapTag($inVal){
  return '<b>'.$inVal.'</b>';
}
$replace = array_map( 'wrapTag' , $search );

$dbContent = str_replace( $search , $replace , $dbContent );

echo $dbContent;

This will split the $search into an array at the spaces, and then wrap each match in the <b> tags.

You could use <b> or <strong> tags (See http://stackoverflow.com/questions/271743/whats-the-difference-between-b-and-strong-i-and-em for a dicussion about them).

Lucanos
`<b>` is deprecated, but that's still the idea. +1
Matchu
He will have more than one word so `preg_replace` with an array of patterns would be a more suitable solution.
Keyo
@Matchu `<b>` hasn't been deprecated, but its use to make text bold has been. It's a common misconception.
alex
@alex, gotcha :) Thanks!
Matchu
A: 

Using str_replace() is problematic as it may cause problems for certain things in strings (such as markup).

What if I search for <a? You can imagine what that will do to anchors in markup.

I reckon the best way is to use JavaScript. It allows you to put something non critical on the client, plus you can server side cache all your articles. It also allows you to update the DOM quickly and easily if they want to remove the highlighting.

Use a recursive DOM function to find the text and wrap it in <span class="highlight /> or similar.

I know you didn't tag this question, jQuery, but I wrote a jQuery plugin that does what you are after.

There is actually not much jQuery use (just for selecting really) so you can dissect the source to get some ideas.

alex
+1  A: 
$search = @$_GET['q'];
$trimmed = trim($search);

function highlight($req_field, $trimmed)  //$req_field is the field of your table
{
        preg_match_all('~\w+~', $trimmed, $m);
        if(!$m)
            return $req_field;
        $re = '~\\b(' . implode('|', $m[0]) . ')\\b~';
        return preg_replace($re, '<b>$0</b>', $req_field);
}

  print highlight($req_field, $trimmed);

In this way, you can bolden the searched keywords. Its quite easy and works well.

Anjali