0

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.

Community
  • 1
  • 1
Ryan Rich
  • 11,637
  • 8
  • 22
  • 31

1 Answers1

1

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

Dave Thomas
  • 3,667
  • 2
  • 33
  • 41
  • Yes this is what I was looking for. I knew I needed a span for the highlighted text but didn't really have any ideas on how to make that work. In your opinion is PHP the best language to accomplish this? – Ryan Rich Mar 28 '12 at 03:25
  • I assumed Php because that is what language is tagged. You could use any server side language to achieve this task or even client side JavaScript. Depends on what your website is programmed in as well. If you need help assessing your situation drop me an email. Cheers :) – Dave Thomas Mar 29 '12 at 04:42