PHPackages                             technically/search-query - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. technically/search-query

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

technically/search-query
========================

Parse plaintext search queries into easy-to-use structures

0.2.0(1mo ago)137↑50%MITPHPPHP ^8.4CI passing

Since Jun 15Pushed 1mo agoCompare

[ Source](https://github.com/technically-php/search-query)[ Packagist](https://packagist.org/packages/technically/search-query)[ RSS](/packages/technically-search-query/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (1)Dependencies (2)Versions (3)Used By (0)

Technically Search Query
========================

[](#technically-search-query)

*🔍 Parse plaintext search queries into easy-to-use filter structures.*

This library takes a human-typed search query string and parses it into a structured `Query` object containing typed filters (`KeywordFilter`, `FieldFilter`). It supports quoted strings, negation, comparison operators, and field-based filtering.

[![Test](https://github.com/technically-php/search-query/actions/workflows/test.yml/badge.svg)](https://github.com/technically-php/search-query/actions/workflows/test.yml)

---

Installation
------------

[](#installation)

```
composer require technically/search-query
```

Requirements:

- PHP 8.4+

---

Quick Start
-----------

[](#quick-start)

```
use Technically\SearchQuery\QueryParser;

$parser = new QueryParser();
$query  = $parser->parse('tag:php -legacy "best practices"');

foreach ($query->filters as $filter) {
    // Filter instances...
}
```

---

Supported Query Syntax
----------------------

[](#supported-query-syntax)

SyntaxParsed As`hello``KeywordFilter('hello')``"hello world"``KeywordFilter('hello world', quoted: true)``-hello``KeywordFilter('hello', exclude: true)``tag:php``FieldFilter('tag', ':', 'php')``-tag:php``FieldFilter('tag', ':', 'php', exclude: true)``year>2020``FieldFilter('year', '>', '2020')``year>=2020``FieldFilter('year', '>=', '2020')``year FieldFilter('tag', ':', 'legacy', exclude: true)

```

### Quoting

[](#quoting)

Double quotes group multiple words into a single token. Quotes can be escaped with `\`.

```
"hello world"            -> KeywordFilter('hello world', quoted: true)
field:"hello world"      -> FieldFilter('field', ':', 'hello world', quoted: true)

```

### Escaping

[](#escaping)

The backslash `\` escape character works both inside and outside quoted strings:

```
apples\ fruits            -> KeywordFilter('apples fruits')
55\"                      -> KeywordFilter('55"')
"hello \"world\""         -> KeywordFilter('hello "world"', quoted: true)

```

The Tolerant Reader
-------------------

[](#the-tolerant-reader)

The parser is built using the [Tolerant Reader](https://martinfowler.com/bliki/TolerantReader.html)design pattern — to be forgiving with malformed input. It never throws.

---

API Reference
-------------

[](#api-reference)

### `QueryParser`

[](#queryparser)

The main entry point for parsing query strings.

```
use Technically\SearchQuery\QueryParser;

$parser = new QueryParser();
$query  = $parser->parse('your search query');
```

The parser accepts an optional `Tokenizer` instance in its constructor. By default, it uses `QueryTokenizer`.

#### Methods

[](#methods)

- `parse(string $query): Query` — Parses a query string into a `Query` object.

---

### `Query`

[](#query)

An immutable value object representing the parsed search query.

```
use Technically\SearchQuery\Query;

$query = new Query([
    new KeywordFilter('php'),
    new FieldFilter('tag', ':', 'tutorial'),
]);
```

#### Properties

[](#properties)

- `public readonly array $filters` — Array of `Filter` instances.

#### Methods

[](#methods-1)

- `static empty(): self` — Create a new empty query.
- `isEmpty(): bool` — Check if the query is empty (has no filters).
- `toString(): string` — Serializes the query back to the search query syntax string.

---

### Filters

[](#filters)

All filters implement the `Technically\SearchQuery\Filters\Filter` marker interface.

#### `KeywordFilter`

[](#keywordfilter)

Represents a free-text keyword search term.

```
use Technically\SearchQuery\Filters\KeywordFilter;

new KeywordFilter('php');
new KeywordFilter('hello world', quoted: true);
new KeywordFilter('legacy', exclude: true);
```

**Properties:**

- `public readonly string $keyword` — The keyword value.
- `public readonly bool $quoted` — Whether the keyword was originally quoted.
- `public readonly bool $exclude` — Whether the keyword is negated.

**Methods:**

- `unquote(): self` — Returns a new instance with `quoted` set to `false`.
- `toString(): string` — Serializes the filter back to query syntax.

#### `FieldFilter`

[](#fieldfilter)

Represents a field-based filter (`field:operator:value`).

```
use Technically\SearchQuery\Filters\FieldFilter;

new FieldFilter('year', '>', '2020');
new FieldFilter('status', ':', 'active', quoted: true);
new FieldFilter('tag', ':', 'legacy', exclude: true);
```

**Properties:**

- `public readonly string $field` — The field name.
- `public readonly FilterOperator $operator` — The comparison operator.
- `public readonly string $value` — The filter value.
- `public readonly bool $quoted` — Whether the value was originally quoted.
- `public readonly bool $exclude` — Whether the filter is negated.

**Methods:**

- `matches(...): bool` — Check whether the filter matches the given properties.
- `unquote(): self` — Returns a new instance with `quoted` set to `false`.
- `toString(): string` — Serializes the filter back to query syntax.

---

Examples
--------

[](#examples)

### Parse a complex query

[](#parse-a-complex-query)

```
use Technically\SearchQuery\QueryParser;
use Technically\SearchQuery\Filters\KeywordFilter;
use Technically\SearchQuery\Filters\FieldFilter;

$parser = new QueryParser();
$query  = $parser->parse('php -legacy "best practices" year>=2020');

foreach ($query->filters as $filter) {
    if ($filter instanceof KeywordFilter) {
        echo "Keyword: {$filter->keyword}"
           . ($filter->exclude ? ' (excluded)' : '')
           . ($filter->quoted ? ' (quoted)' : '')
           . "\n";
    } elseif ($filter instanceof FieldFilter) {
        echo "Field: {$filter->field} {$filter->operator->value} {$filter->value}"
           . ($filter->exclude ? ' (excluded)' : '')
           . ($filter->quoted ? ' (quoted)' : '')
           . "\n";
    }
}
// Output:
// Keyword: php
// Keyword: legacy (excluded)
// Keyword: best practices (quoted)
// Field: year >= 2020
```

### Serialize filters back to strings

[](#serialize-filters-back-to-strings)

```
$filter = new FieldFilter('tag', ':', 'hello world', quoted: true, exclude: true);
echo $filter->toString(); // -tag:"hello world"

// Or serialize an entire Query back to string:
$query = new Query([
    new KeywordFilter('php'),
    new FieldFilter('year', '>', '2020', exclude: true),
]);
echo $query->toString(); // php -year>2020
```

### Custom tokenization

[](#custom-tokenization)

```
use Technically\SearchQuery\QueryParser;
use Technically\SearchQuery\Contracts\Tokenizer;

class MyCustomTokenizer implements Tokenizer
{
    public function tokenize(string $query): iterable
    {
        // Custom tokenization logic...
    }
}

$parser = new QueryParser(new MyCustomTokenizer());
```

---

Running Tests
-------------

[](#running-tests)

```
composer tests
```

Tests are written with [Pest PHP](https://pestphp.com/).

---

License
-------

[](#license)

MIT

Credits
-------

[](#credits)

Implemented by 👾 [Ivan Voskoboinyk](https://voskoboinyk.com/).

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance91

Actively maintained with recent releases

Popularity12

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

44d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/370680?v=4)[Ivan Voskoboinyk](/maintainers/e1himself)[@e1himself](https://github.com/e1himself)

---

Top Contributors

[![e1himself](https://avatars.githubusercontent.com/u/370680?v=4)](https://github.com/e1himself "e1himself (28 commits)")

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/technically-search-query/health.svg)

```
[![Health](https://phpackages.com/badges/technically-search-query/health.svg)](https://phpackages.com/packages/technically-search-query)
```

###  Alternatives

[sauladam/shipment-tracker

Parses tracking information for several carriers, like UPS, USPS, DHL and GLS by simply scraping the data. No need for any kind of API access.

9843.5k](/packages/sauladam-shipment-tracker)[jstewmc/rtf

Read and write Rich Text Format (RTF) documents with PHP

45153.1k6](/packages/jstewmc-rtf)[tcds-io/php-jackson

A lightweight, flexible object serializer for PHP, inspired by FasterXML/jackson

113.2k10](/packages/tcds-io-php-jackson)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
