0

For the website I'm working on, I've included a "search the site" section. Once the user searches a keyword or a phrase, the php processes all the content in the mysql database and prints out the title, content and a link to the page with the article containing that specific text.

I'll include the most relevant part of the code from that php file:

<?php
// get results from database
  $result = mysql_query($query) or die("Couldn't execute query");
  
// display the results
  $count=0;
  while ($row = mysql_fetch_array($result)) {
  if ($count != 5) {
  $count++;
  $hometitle = $row["home_title"];
  $homecontent = nl2br($row["home_content"]);
  echo "<p><b><u>Results</u></b><br><br>Title:<br>$hometitle<br><br>Content:<br>$homecontent<br>" . "<a href=\"../index.php\">See Full Content</a></p>";
  }
  }
?>

Sorry for that messy looking "echo". But what I want to do is for the keyword which is searched for to be highlighted in the results.

I'm guessing the algorithm for it be something like converting the resulting value into an array, boldening the keywords then again changing it into a string before printing again. However, I've not been able to do this successfully.

Help Please!

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by asif49
1

I don't think you HAVE to make it that complicated with an algorithm. Instead, you could try using PHPs str_replace() function, where if a string "possesses" the keyword, add some css styling to it.

str_replace('haystack', 'needle', 'replace with what');

$keyword = "awesome";
$string = "This website article is awesome!";
$highlight = str_replace($string, $keyword, "<strong>$keyword</strong");

print $highlight;

I haven't tested this code, but off the top of my head this will hopefully lead you in the right direction. Happy coding.

Votes + Comments
Gave me great help, saved me hours of time!
0

Thanks a lot for that info^^ otherwise I would've stayed up the whole night frustrated, and trying to write some complicated algorithm to solve this. This was an easy resolve.

Your syntax was just a little bit off, but a quick google search corrected that for me. It's: str_replace (search_for, replace_with, apply_to);

Thanks again!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.