我正在做一个员工管理项目,客户提出了一项新要求,希望允许他们的用户进行自定义布尔搜索。
基本上允许他们使用: AND、OR、NOT、括号和引号。
最佳实现方法是什么?我已经查看了mysql,但它们使用了不同的语法。
这是测试场景:
需求:搜索来自新加坡的Magicians或Barbarians,其等级为Elite或Veteran Level
布尔字符串:("Magician" OR "Barbarian") AND (Elite OR "Veteran Level") and Singaporean
这是我将考虑修改的代码之一,我从Pure PHP based boolean search for strings中获取。
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;
}
[Magician,OR,Barbarian]
),由于OR是二元运算符,因此您可以获取其左右两侧进行OR比较的内容。NOT是右结合的一元运算符,因此您需要将其与右侧的第一个内容匹配。再次强调,这并不容易。 - apokryfos