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:

// get results from database
  $result = mysql_query($query) or die("Couldn't execute query");
// display the results
  while ($row = mysql_fetch_array($result)) {
  if ($count != 5) {
  $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!

Recommended Answers

All 2 Replies

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.

commented: Gave me great help, saved me hours of time! +3

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!

Be a part of the DaniWeb community

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