PHP library for parsing Google-like search operators?

I want to create a PHP search function, but using Google-like operators. For instance:

these words "this phrase" location:"Los Angeles" operator:something 

It is important that operators like location: support values ​​with spaces in them (hence the quotation marks in this example), so I cannot just split or use standard tokens. I would suggest that someone at some point created a library for this, but I cannot find.

Or, if it does not require a library, a good way to do this would be a good one.

This is just the parsing of the search query I need; that is, from the request above it would be nice to get an array consisting of:

 [0] => these [1] => words [2] => "this phrase" [3] => location:"Los Angeles" [4] => operator:something 

From this, I can build a search function for the database.

+6
source share
1 answer

You can start with str_getcsv () and use a space as a separator, but you may need to pre-process the location and operator to process the quote in this particular case.

 <?php $str = 'these words "this phrase" location:"Los Angeles" operator:something'; // preprocess the cases where you have colon separated definitions with quotes // ie location:"los angeles" $str = preg_replace('/(\w+)\:"(\w+)/', '"${1}:${2}', $str); $str = str_getcsv($str, ' '); var_dump($str); ?> 

Output

 array(5) { [0]=> string(5) "these" [1]=> string(5) "words" [2]=> string(11) "this phrase" [3]=> string(20) "location:Los Angeles" [4]=> string(18) "operator:something" } 
+12
source

All Articles