phpmysqlstrchrstripos

strpos() show n character before and after specified word


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.


Solution

  • 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);