0

After some search and googling I found code for highlighting and limiting the search results within a text similar to this one:

$text = preg_replace("/^.*?(.{0,100})\b($word)\b(.{0,100}).*?$/mi", '\1<span class="highlight_word">\2</span>\3', $text);

Unfortunately I always get the complete $text back even though the contents of $word is placed within the span as intended.

My question is now how I may reduce the contents of $text to just show 100 characters before and after the search result (contents of $word). I also checked the regular expression in several variants using a webportal and got the desired result. Nevertheless my php code is not showing what is intended. Any help is really appreciated as I assume there is a very stupid error on my side.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • How's this related to mysql? What is `$text`? What is intended and what is displayed? – chris85 Apr 26 '17 at 19:59
  • After your preg_replace, get the position of $word, then use substr to get the 100 before and 100 after. IOW, if $p1 = the position of $word in $text, $rslt = substr($text,$p1 - 100, 200 + strlen($word)) or similar. – Sloan Thrasher Apr 26 '17 at 20:06
  • 1
    Possible duplicate of [limit text length in php and provide 'Read more' link](http://stackoverflow.com/questions/4258557/limit-text-length-in-php-and-provide-read-more-link) – Otávio Barreto Apr 26 '17 at 20:38

1 Answers1

1

When you use the m flag, ^ and $ match the beginning and end of lines, not the beginning and end of the string. So this only matches and replaces in a single line of $text at a time, and non-matching lines are left alone.

If you want to match across multiple lines, use the s modifier. That permits . to match newlines, but ^ and $ still match only the beginning and end of $text.

Barmar
  • 741,623
  • 53
  • 500
  • 612