popel_ok
popel_ok

Reputation: 1

php limiting search results in text

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.

Upvotes: 0

Views: 48

Answers (1)

Barmar
Barmar

Reputation: 780724

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.

Upvotes: 1

Related Questions