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's important that operators like location: support values with spaces in them (hence the quotes in this example), so I can't just to a split or use standard tokens. I'd imagine someone at some point has created a library for doing this, but I can't find any.
Or if it doesn't require a library, a nice way to do this would be good.
It's just the parsing of a search query that I need; i.e. from the query above it would be fine to get an array consisting of:
[0] => these
[1] => words
[2] => "this phrase"
[3] => location:"Los Angeles"
[4] => operator:something
From that I can build a search function for the database.
inurl: Find pages with a certain word (or words) in the URL. For this example, any results containing the word “apple” in the URL will be returned.
You can start with str_getcsv() and use a space as the delimiter, but you may have to preprocess the location & operator to handle the quotes in that particular case.
<?php
$str = 'these words "this phrase" location:"Los Angeles" operator:something';
// preprocess the cases where you have colon separated definitions with quotes
// i.e. 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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With