0

I found this bit of code on stackoverflow at Best practices on displaying search results with associated text snippets from actual result

However it doesn't quite do what i want. It displays the text around a given search term, but there are two problems

1) I want whole words only; 2) It doesn't limit the characters after the search term, only the ones before

Here's the code below. How can I edit it to solve the two problems? Thanks in advance:

$text = 'This is an example text page with content. It could be red, green or blue or some other random color. It dont really matter.';
$keyword = 'red'; 
$size = 15; // size of snippet either side of keyword
$snippet = '...'.substr($text, strpos($text, $keyword) - $size, strpos($text, $keyword) + sizeof($keyword) + $size).'...'; 
$snippet = str_replace($keyword, '<strong>'.$keyword.'</strong>', $snippet); 
echo $snippet; 
Community
  • 1
  • 1
Steven
  • 1,567
  • 4
  • 14
  • 17

2 Answers2

1
$snippet = preg_replace(
    '/^.*?\s(.{0,'.$size.'})(\b'.$keyword.'\b)(.{0,'.$size.'})\s.*?$/',
    '...$1<strong>$2</strong>$3...',
    $text
);

This will produce: ...It could be <strong>red</strong>, green or blue.... It's the \s character classes that limit the 15-characters to occurring after a word break.

amphetamachine
  • 27,620
  • 12
  • 60
  • 72
0

I made a post here: How to generate excerpt with most searched words in PHP?

The messiest code that I have ever written might work for you. I really encourage you to factor out much of the repeated code I have in there.

Community
  • 1
  • 1
erisco
  • 14,154
  • 2
  • 40
  • 45