How to make text entered into a search engine bold in PHP

Home > Search > How-to

What this code does is to first store the input of the text entered into the search engine into the $string variable. Next, the preg_split command stores each word into it's own variable. For example, let's say Where is Super Man is entered into the search engine.  The $keywords variable will create a variable for each word.

  • $keyword[0] = Where
  • $keyword[1] = is
  • $keyword[2] = Super
  • $keyword[3] = Man

The $sql statement first finds a perfect match with $keyword[0], and then finds anything else in the database which is like the additional keywords.

The $original, $new and str_ireplace commands simply makes the keywords bold.

$string = $_POST['keyword'];
$keywords = preg_split('/[\s,]+/', $string);
$sql = "select * from tablename where match (Title) against ('$keywords[0]' in boolean mode) 
and Title like '%$keywords[1]%'
and Title like '%$keywords[2]%'
and Title like '%$keywords[3]%'
and Title like '%$keywords[4]%'
and Title like '%$keywords[5]%' ";
$sql_query = mysqli_query($con, $sql);

while ($row = mysqli_fetch_array($sql_query)) {
  $original = array($keywords[0],$keywords[1],$keywords[2],$keywords[3],$keywords[4],$keywords[5]);
  $new = array('<b>'.$keywords[0].'</b>','<b>'.$keywords[1].'</b>','<b>'.$keywords[2].'</b>','<b>'.$keywords[3].'</b>','<b>'.$keywords[4].'</b>','<b>'.$keywords[5].'</b>',);
echo str_ireplace($original, $new, $row['Title']);


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter in the box below so that we can be sure you are a human.