PHPackages                             hosmelq/search-syntax-parser - 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. hosmelq/search-syntax-parser

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

hosmelq/search-syntax-parser
============================

Parse search queries into structured data with field searches, boolean logic, ranges, lists, and adapters.

v1.0.0(8mo ago)7785MITPHPPHP ^8.2CI passing

Since Sep 11Pushed 8mo agoCompare

[ Source](https://github.com/hosmelq/search-syntax-parser)[ Packagist](https://packagist.org/packages/hosmelq/search-syntax-parser)[ RSS](/packages/hosmelq-search-syntax-parser/feed)WikiDiscussions main Synced 1mo ago

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

Search Syntax Parser
====================

[](#search-syntax-parser)

Parse search queries into structured data with support for field searches, boolean logic, range comparisons, and multiple output formats.

Introduction
------------

[](#introduction)

Use a concise, expressive query language to build structured queries. It supports field-specific searches, boolean operators, ranges, existence checks, and multi-value lists, and outputs to multiple formats via adapters.

```
use HosmelQ\SearchSyntaxParser\SearchParser;

$result = SearchParser::query('age:>25 AND name:john')->build();
```

It returns a normalized PHP array describing the query.

Requirements
------------

[](#requirements)

- PHP 8.2+

Installation &amp; setup
------------------------

[](#installation--setup)

Install the package via composer:

```
composer require hosmelq/search-syntax-parser
```

Basic usage
-----------

[](#basic-usage)

### Getting started

[](#getting-started)

Create a parser from a query string and build it using the default array adapter:

```
use HosmelQ\SearchSyntaxParser\SearchParser;

$result = SearchParser::query('title:Coffee AND price:10')->build();      // Greater than
SearchParser::query('price:>=10')->build();     // Greater than or equal
SearchParser::query('price:100')->build();

// Supports quoted values
SearchParser::query('category:"Home & Garden","Sports & Outdoors"')->build();
```

#### Exists queries

[](#exists-queries)

Search for documents with non-null values in specified fields using wildcard syntax:

```
SearchParser::query('category:*')->build();      // Field has any value
SearchParser::query('NOT discount:*')->build();  // Field doesn't exist
```

#### Range queries

[](#range-queries)

Search within value ranges using boundary operators:

```
SearchParser::query('price:[10 TO 50]')->build();                 // Numeric range
SearchParser::query('date:[2025-01-01 TO 2025-12-31]')->build();  // Date range
```

#### Terms

[](#terms)

Search using basic terms that match default searchable fields:

```
SearchParser::query('coffee')->build();
```

#### Modifiers (NOT)

[](#modifiers-not)

Negate terms or subqueries using `-` or `NOT`:

```
SearchParser::query('NOT title:Coffee')->build();  // NOT modifier
SearchParser::query('-title:Coffee')->build();     // - modifier (equivalent)
```

### Field validation

[](#field-validation)

Restrict which fields can be used and validate their values using `AllowedField` helpers:

```
use HosmelQ\SearchSyntaxParser\SearchParser;
use HosmelQ\SearchSyntaxParser\Validation\AllowedField;

$parser = SearchParser::query('age:25 AND status:ACTIVE')->allowedFields([
    AllowedField::integer('age')->min(0),
    AllowedField::in('status', ['ACTIVE', 'DRAFT', 'PENDING']),
    AllowedField::string('name')->size(2),
]);

$result = $parser->build(); // throws if any value is invalid or a field is not allowed
```

You can also map external field names to internal ones:

```
$parser = SearchParser::query('age:10')->allowedFields([
    AllowedField::integer('age', 'user_age'),
]);

$result = $parser->build();
// The array adapter will output the internal name "user_age" for the field
```

### Array item validation (each and at)

[](#array-item-validation-each-and-at)

For array fields, use `each()` to validate every item and `at(index)` to validate specific positions.

Per‑item rules with `each()`:

```
use HosmelQ\SearchSyntaxParser\SearchParser;
use HosmelQ\SearchSyntaxParser\Validation\AllowedField;

$parser = SearchParser::query('tags:alpha,beta')
    ->allowedFields([
        AllowedField::array('tags')
            ->max(5)
            ->each(fn ($rules) => $rules->string()->max(10)),
    ]);

$result = $parser->build();
```

Index‑specific rules with `at()` (tuple‑like arrays):

```
use HosmelQ\SearchSyntaxParser\SearchParser;
use HosmelQ\SearchSyntaxParser\Validation\AllowedField;

$parser = SearchParser::query('location:37.7749,-122.4194')
    ->allowedFields([
        AllowedField::array('location')
            ->size(2)
            ->at(0, fn ($rules) => $rules->numeric()->between(-90, 90))
            ->at(1, fn ($rules) => $rules->numeric()->between(-180, 180)),
    ]);

$result = $parser->build();
```

### Custom adapters

[](#custom-adapters)

Create custom output formats by implementing the adapter interface:

```
use HosmelQ\SearchSyntaxParser\Adapter\QueryAdapterInterface;
use HosmelQ\SearchSyntaxParser\AST\Node\NodeInterface;
use HosmelQ\SearchSyntaxParser\SearchParser;

class EloquentAdapter implements QueryAdapterInterface
{
    public function build(NodeInterface $ast): mixed
    {
        // Convert the AST to your preferred format
        return ['where' => ['name', 'john']];
    }
}

$parser = SearchParser::query('name:john');

$parser->extend('eloquent', fn () => new EloquentAdapter());

$result = $parser->build('eloquent');
```

### Error handling

[](#error-handling)

Handle parsing errors with `ParseException`:

```
use HosmelQ\SearchSyntaxParser\Exception\ParseException;
use HosmelQ\SearchSyntaxParser\SearchParser;

try {
    SearchParser::query('invalid:syntax:here')->build();
} catch (ParseException $e) {
    echo "Parse error: " . $e->getMessage();
}
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG.md](CHANGELOG.md) for more information on what has changed recently.

Credits
-------

[](#credits)

- [Hosmel Quintana](https://github.com/hosmelq)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance61

Regular maintenance activity

Popularity19

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

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

Unknown

Total

1

Last Release

249d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/97fd048037c6d5ccfeebf11961838d5db2dca1baca14fefa373230b301389a03?d=identicon)[hosmelq](/maintainers/hosmelq)

---

Top Contributors

[![hosmelq](https://avatars.githubusercontent.com/u/1166143?v=4)](https://github.com/hosmelq "hosmelq (2 commits)")

---

Tags

astdsllexerquery-languagequery-parsersearch-querysearch-syntaxtokenizerlexertokenizerDSLastquery parserquery-languagesearch-querysearch-syntax

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/hosmelq-search-syntax-parser/health.svg)

```
[![Health](https://phpackages.com/badges/hosmelq-search-syntax-parser/health.svg)](https://phpackages.com/packages/hosmelq-search-syntax-parser)
```

###  Alternatives

[doctrine/lexer

PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.

11.2k910.8M118](/packages/doctrine-lexer)[behat/gherkin

Gherkin DSL parser for PHP

1.1k176.3M97](/packages/behat-gherkin)[creof/geo-parser

Parser for geography coordinate strings

624.4M15](/packages/creof-geo-parser)[creof/wkt-parser

Parser for well-known text (WKT) object strings

554.8M16](/packages/creof-wkt-parser)[palantirnet/drupal-rector

Instant fixes for your Drupal code by using Rector.

1544.2M20](/packages/palantirnet-drupal-rector)[yethee/tiktoken

PHP version of tiktoken

1583.1M15](/packages/yethee-tiktoken)

PHPackages © 2026

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