PHP search within a string

I have a chunk of text like this:

$text = "Internal tissue sealants and hemostasis are relatively underpenetrated, although their use has grown rapidly. In 2012
, internal tissue sealants were used in just over 3% of the procedures listed above. Healthy growth is expected throughout 
the forecast period, driven by growing adoption in key procedures, such as neurological surgeries and thoracic operations; 
increasing use as an adjunct to hemostasis; and broadening indications. The value of revenues per procedure is expected to 
remain relatively flat, below $400. Sales are expected to reach $370 million in 2018. Exhibit 4-7 presents the market forecast for 
external and internal tissue sealants.";

And I would like to use PHP to search through it based on a word and return a snippet of the sentence where it appears and show a result like this:

Search word: hemostasis

  1. …Internal tissue sealants and hemostasis are relatively underpenetrated…
  2. …use as an adjunct to hemostasis; and broadening indications…

Any ideas?

The quick answer is use strpos which returns the position, then use substr.

I think you could do it with one of the regex methods, but can’t remember off hand which…

Consider breaking the text up into sentences. (split on the .)

Then select only those sentences containing the target term.

Then highlight the term.

Traversing back and forward for n chars will take some more work, but is doable.

Tokenize the string (split on ’ ')
Preg_grep on “~.“.$term.”.~”; this gives you the keys of the matching tokens.
foreach key found,
Get the implosion (on ’ ') of the array_slice from max($key - $words_before,0) for length $words_to_include.
Str_replace your term with <strong>$term</strong>.

This will give you full words instead of characters before and after. echo “…”.$result.“…” and you’ve got the output you wanted.

thanks guys, I got this… any improvements?

<?php


function Search($text, $search){
	$arr = explode($search, $text);
    $out = array();
    for ($i = 0; $i < count($arr)-1; $i++) {
      $out[] = "...".substr($arr[$i], -30)." ".$search." ".substr($arr[$i+1], 0, 30)."...";
    }
    return $out;
}

$text="Internal tissue sealants and hemostasis are relatively underpenetrated, although their use has grown rapidly. In 2012, internal tissue sealants were used in just over 3% of the procedures listed above. Healthy growth is expected throughout the forecast period, driven by growing adoption in key procedures, such as neurological surgeries and thoracic operations; increasing use as an adjunct to hemostasis; and broadening indications. The value of revenues per procedure is expected to remain relatively flat, below $400. Sales are expected to reach $370 million in 2018. Exhibit 4-7 presents the market forecast for external and internal tissue sealants.";
$search="hemostasis";

$return=(Search($text, $search));
$i=0; foreach($return as $row) { $i++; echo $i.") ".$row."<br>"; }

?>