OzzC
OzzC

Reputation: 821

show a piece of text after the searched word

When user search for some word and submit my form Im doing a select to show some columns of my news table where title or content is like searched word.

And then I have a list where I want to show a piece of text containing the searched word.

For example if user search for word "title" and I have in my news table a record with title "this title is not currently available for purchase".

I want to show for example 25 chars after my searched word, in this case: "title is not currently"

Do you know some way to do something like this?

$search = $url[1];
$read = $pdo->prepare("SELECT * FROM news WHERE status = ? AND (title LIKE ? OR content LIKE ?) ORDER BY date DESC"); 
$read->bindValue(1, '1');
$read->bindValue(2, "%$search%", PDO::PARAM_STR);
$read->bindValue(3, "%$search%", PDO::PARAM_STR);
$read->execute();

while($result = $read->fetch(PDO::FETCH_ASSOC)){
  echo '<a href="'.BASE.'/'.$result['link'].'">'.$result['title'].'</a>';
  //here I want to show a <span>.'$search'.</span> with my searched word more 25chars
}

Upvotes: 0

Views: 40

Answers (1)

Tesserex
Tesserex

Reputation: 17314

The PHP function strpos will tell you where the search was in the string. Then use substr to take that plus 25 characters.

$searchPos = strpos($search, $title);
$searchLen = strlen($search);

$result = substr($title, $searchPos, $searchLen + 25);

Upvotes: 4

Related Questions