I am creating a basic search feature for my framework and looking for some advice as to how to display the search results the best way (google style). My MYSQL query returns distinct pages based on the search query. The results back from MySQL is perfect, I just need to do the following:
An example could be that someone search the term "Hello World". My search results will return all rows which contain both "hello" and "world".
What I am trying to achieve is:
- Highlight the words in the search query but only a fragment of the results. I would like to only return 200 characters and highlight (bold) the first occurrence of any of the words in the search term.
- The copy displayed would have been created in a CMS and has html tags. I am able to strip the html tags before displaying it but want to get feedback if I am doing it the correct way.
The code I am using currently is:
// The query string:
<?php $q = urldecode($_GET['qString']); ?>
// Run a loop through the results:
<?php foreach ($this->get("pageResults") AS $result): ?>
// a clickable H3 to the actual page:
<h3><?= $this->html->link($result['sub_heading'] . " " . $result['heading'], array("controller" => "pages", "action" => "viewer", "properties" => array($result['name']))) ?></h3>
<?php
// Strip all html characters as the content comes from an WYSIWYG editor:
$value = preg_replace('/<[^>]*>/', '', $result['content']);
// Find the position within the text:
$position = stripos($value, $q);
// If a positive position, display 200 characters and start -100 from the first occurance
if ($position == true) {
$string = substr($value, $position - 100, 200);
} else {
$string = " ... ";
?>
<p><?= $string ?></p>
<hr />
<?php endforeach; ?>
The main problem I run into here is:
- The search results would have returned rows even if the query string
was not precise (so it will return a result if the column contained
"hello" and "world" whereas
stripos
will only find "hello world". - I do'nt know the best way to wrap
<strong></strong>
tags around the first occurrence of a word or phrase within the stripped html. I understand that this may be a tricky thing to achieve especially due to the occurrence issue. I can live without this feature but if there is a nifty way of doing it that would be great :)
Any ideas would greatly be appreciated!