I have a large text string which is queried from a database. It can be several thousand words long. As of right now, when the search is run, it pulls all of the text and then prints the first 150 characters:

echo '<span class="line3">'. strip_tags(truncateText($sermontext, 150)) .'</span>';

The truncateText() function is as follows:

// return with no change if string is shorter than $limit
if(strlen($string) <= $limit) return $string;

// is $break present between $limit and the end of the string?
if(false !== ($breakpoint = strpos($string, $break, $limit))) {
     if($breakpoint < strlen($string) - 1) {
          $string = substr($string, 0, $breakpoint) . $pad;
     }
}
return $string;

The search works great, and the output is OK, but as it is, it outputs from the beginning of the text. Now this gets the job done, but I want to make it more intuitive for the user. I want the text that is printed to be positioned around the word or phrase the user searched for. In other words, if the user searches for "someword", the result would be:

blah blah blah blah someword blah blah blah blah... (and of course I'd highlight "someword" in a different color). I'm guessing that strpos or stripos need to be implemented, but I'm at a loss as to how to accomplish this.

thanks!

Recommended Answers

All 2 Replies

If you still want the 150 characters, you could subtract the length of the search from 150 and divide by 2. Then you can substract that value from strpos and take the 150 characters from there.

There are of course the edge cases which require some additional calculation, for example search at the start/end of the string.

Sounds great I'll give it a shot! Thanks!

Be a part of the DaniWeb community

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