Search code examples
phpjqueryajaxsearchspotlight

Creating a "spotlight search" in PHP


I'm working on an E-Book that will be published to my website. I want to mimic OSX spotlight feature where someone can use a my fixed search bar and input text that is then highlighted on the page for them. I was trying to use Sphider but no such luck on getting this result.

•found this similar thread but not exactly what I'm looking for.


Solution

  • You could use a string replace to surround all text that needs to be highlighted with a span tag. Then create a CSS class for that span tag.

    <?php
    
    $searchString = $_POST['search'];
    $EBOOK = str_replace($searchString, "<span class='highlighted'>$searchString</span>", $EBOOK);
    

    Then some CSS

    .highlighted {
      background-color:yellow;
    }
    

    To take it to the next step you could use javascript to scroll the user's web browser to the first location of a span.highlighted.

    Note I wouldn't use a regular expression to replace search string value (ie preg_replace) because the user's search input could contain special characters used by regex that may need to be escaped.

    This is all theoretical of course... based on your question.

    Edit: just thought of something, Ebook content will contain HTML tags so if you were to use a string replace function like I suggested. Take into consideration to not allow the tags to be searched and replaced. A regular expression replace may be needed in this case