-2

I wrote a simple search engine and want to show some text in result, actually I want to show 200 character before SEARCH QUERY and 200 character after SEARCH QUERY.

Example:

SEARCH QUERY: TEST

RESULT:

BLAH BLAH BLAH BLAH BLAH BLAHBLAH BLAH BLAHBLAH BLAH BLAHBLAH BLAH BLAHBLAH BLAH BLAHBLAH BLAH BLAH BLAH BLAH BLAH TEST BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH.

I want this output:

... BLAH BLAH BLAH BLAH TEST BLAH BLAH BLAH BLAH ...

with 3 dots before and after.

$text= $row["text"];
$find = $term;
$result = strpos($text, $find);

But I don't know how to set it to show 200 char before $term and 200 char after $term in $text.

Pedram
  • 15,766
  • 10
  • 44
  • 73

1 Answers1

2

you can use substr()

The substr() function returns a part of a string.

substr(string,start,length) 

Read more

start from position of text. minus 200(length) will get the chars before and plus 200(length) will get the chars after it (here length of text is added because we are starting at first letter of $text)

$text= $row["text"];
$find = $term;
$result = strpos($text, $find);
echo substr($text,($result-200>0)?($result-200):0,200)." ".$find." "
.substr($text,$result+strlen($find),200);
A.B
  • 20,110
  • 3
  • 37
  • 71
  • looks great but kinda not working, it will echo whole text just start with $term. – Pedram Mar 29 '15 at 12:38
  • This is GREAT. How would I use this with multiple words? For example if we are looking for the word 'Happy' in huge text and you wanted this function for every word of happy, then how would we do this? – Papa De Beau Jul 07 '18 at 18:28