基于纯 PHP 的字符串布尔搜索 [英] Pure PHP based boolean search for strings

查看:65
本文介绍了基于纯 PHP 的字符串布尔搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,需要在纯 PHP 中进行一些基本的布尔搜索.这意味着我有简单的字符串,我想对它们提供一些简单的布尔搜索.不涉及数据库或其他索引引擎,所以请不要参考 MySQL 布尔搜索或 lucene.

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.

最后,类似于以下代码的内容应该打印 containsnot found.

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

推荐答案

对于一个简单的实现,您可以只拆分条件(考虑引号)并遍历每个条件以查看它是否匹配:

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

这篇关于基于纯 PHP 的字符串布尔搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆