PHP fulltext search using AND OR NOT operators

Viewed 28

Newbie question: I am trying to implement a full-text search on a search string with php and eloquent.

$searchstring = "+(victim suspect) +crime -covid";
$searchresult = RssItem::whereRaw("MATCH (description) AGAINST ('$searchstring' IN BOOLEAN MODE)")->get();

I want my users to be able to set a search string like this:

$searchstring = "(victim OR suspect) AND crime NOT covid";

Is there a simple way of transforming the user input to a boolean full-text search string for mysql in php?

1 Answers

I have accomplished it with the following:

  $searchstring = '(victim OR suspect) AND crime NOT covid';
  $searchstring = str_replace(" OR ", ' ', $searchstring);
  $searchstring = str_replace(" AND ", ' +', $searchstring);
  $searchstring = str_replace(" NOT ", ' -', $searchstring);
  $searchstring = '+'.$searchstring;

  $searchresult = RssItem::whereRaw("MATCH (description) AGAINST ('$searchstring' IN BOOLEAN MODE)")->get();

But maybe there is a better way? :-)

Related