Reputation: 1222
I have a long chunk of text that came back from a search query. I'd like to display a snippet of the text, not the entire thing, and highlight the search query within the snippet. I realize that decided what part of the text to slice can be complicated, and I was hoping for any ideas on how do to this?
Thanks!
Upvotes: 0
Views: 410
Reputation: 53940
for example
$text = "
I have a long chunk of text that came back from a search query. I'd like to display a
snippet of the text, not the entire thing, and highlight the search query within the
snippet. I realize that decided what part of the text to slice can be complicated, and
I was hoping for any ideas on how do to this?
";
$query = "the text";
preg_match("~\b.{0,20}$query.{0,20}\b~", $text, $m);
echo str_replace($query, "<strong>$query</strong>", $m[0]);
Upvotes: 1