Reputation: 1566
I have a project where I need some basic boolean search in pure PHP. It means I have plain strings I want to offer some simple boolean search on them. No database or other indexing engine is involved, so please don't refer to MySQL boolean search or lucene.
At the end something like the following code should print contains
and not found
.
$search = 'foo -bar "must have" -"must not have"';
$contentFound = 'This is some foo text you must have.';
$contentNotFound = 'This is some bar text you must have.';
if ($this->booleanSearch($contentFound, $search)) {
echo 'contains';
} else {
echo 'not found';
}
if ($this->booleanSearch($contentNotFound, $search)) {
echo 'contains';
} else {
echo 'not found';
}
Upvotes: 1
Views: 1159
Reputation: 2596
For a simple implementation you could just split the criteria (taking into account the quotes) and iterate over each criterion to see whether it matches or not:
function booleanSearch($content, $search) {
$criteria = str_getcsv($search, ' ');
while ($criteria) {
$not = false;
$q = array_shift($criteria);
if (substr($q, 0, 2) === '-"') {
$not = true;
while (substr($q, -1) != '"') {
$q .= " " . array_shift($criteria);
}
$q = substr($q, 2, -1);
}
else if (substr($q, 0, 1) === '-' && strpos($q, ' ') === false) {
$not = true;
$q = substr($q, 1);
}
$found = strpos($content, $q) !== false;
if ($found === $not) {
return false;
}
}
return true;
}
Upvotes: 2