Pure PHP based boolean search for strings

余生颓废 提交于 2019-12-24 13:25:54

问题


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';
}

回答1:


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;
}


来源:https://stackoverflow.com/questions/36565455/pure-php-based-boolean-search-for-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!