SugarFuzzy
Fuzzy string matching with matched character indices plus the match score
Fuzzy string matching that returns matched character indices plus the match score. The matcher extracts the Smith-Waterman core from sugar-forms and adds a second algorithm, Sahilm, whose scoring shape follows sahilm/fuzzy. The matched indices enable filter-highlighting UIs that score-only matchers cannot offer. The back-compat shims in sugar-forms and sugar-treelist delegate here, and new code should depend on sugar-fuzzy directly.
Install
composer require sugarcraft/sugar-fuzzy
The manifest requires PHP ^8.3 and nothing else.
Quickstart
use SugarCraft\Fuzzy\Matcher\SmithWatermanMatcher;
use SugarCraft\Fuzzy\Highlighter;
$matcher = new SmithWatermanMatcher();
// Single match: returns null when no match
$result = $matcher->match('foo', 'foobar');
// $result->score === 19 (3 × matchScore + 2 × adjacentBonus = 19)
// $result->indices() === [0, 1, 2] (0-based character positions)
// $result->haystack === 'foobar'
// Match all candidates, sorted by score desc then candidate asc
$results = $matcher->matchAll('ab', ['apple', 'banana', 'cabbage']);
// cabbage (11, the adjacent "ab") before apple (3) and banana (3)
// Opt in to full-query mode for type-to-filter pickers: every query
// character must land, in order
$picker = SmithWatermanMatcher::new()->withRequireFullQuery();
$picker->match('bxz', 'abcdef'); // null — "x" and "z" never land
$picker->match('gst', 'git status')->indices(); // [0, 4, 5]
// Use Highlighter to mark matched runs with ANSI codes
$highlighter = new Highlighter();
echo $highlighter->highlight($result, fn($s) => "\e[1;31m{$s}\e[0m");
// Output: 'foobar' with positions [0,1,2] highlighted in bold red
// The highlighter is presentation-neutral: sanitize candidate text (strip
// \x1b/control bytes) before display — see Security below
Concepts
A matcher takes a query and a candidate and returns a MatchResult or null. The result carries a score, which is higher for better matches, and the 0-based code-point offsets of the matched characters in the original candidate. Matching is case-insensitive by default, and the offsets stay valid even when the case fold would change the length of a string.
The two algorithms differ in what they accept. Smith-Waterman is local alignment: by default a candidate matches as soon as any run of the query aligns with it, so match('bxz', 'abcdef') scores 3 on the b alone. Full-query mode makes it require the whole query. Sahilm always requires the whole query to land, in order. Pick the algorithm by the behavior you want, not by the score.
Scores have no absolute meaning. Compare them only within one matcher and one weight profile, and use matchAll() to rank candidates for the same query.
Tasks
Rank candidates for an autocomplete list
matchAll() returns the survivors sorted by score, highest first. Equal scores fall back to the candidate in ascending order, and numeric-looking candidates sort numerically. A $limit keeps only the best N. The runnable example examples/rank-matches.php shows the ranking with a highlighter.
Build a type-to-filter picker
Use SmithWatermanMatcher::forFiltering(), which turns on full-query mode. A candidate survives only when every typed character lands, in order. examples/full-query-picker.php shows the difference against local alignment.
Match file paths
Use SahilmMatcher for paths. Its separator and camelCase bonuses reward a query that lines up with word starts. examples/sahilm-paths.php ranks a list of files, selecting the matcher through FuzzyMatcherFactory::named().
Tune the weights
use SugarCraft\Fuzzy\Matcher\SmithWatermanMatcher;
use SugarCraft\Fuzzy\ScoringProfile;
$strict = new SmithWatermanMatcher(ScoringProfile::strict());
$custom = new SmithWatermanMatcher(ScoringProfile::canonical()->withAdjacentBonus(8));
Profiles are immutable, so with*() returns a copy. The matcher keeps the profile it was built with.
Key classes
| Class | Method | Description |
|---|---|---|
| FuzzyMatcher | match(string $query, string $candidate): ?MatchResult | Single match, or null when there is none. |
| FuzzyMatcher | score(string $query, string $candidate): int | The score match()?->score ?? 0 would give, without building the traceback. Part of the interface, so both matchers implement it. |
| FuzzyMatcher | matchAll(string $query, iterable $candidates, ?int $limit = null, int $minScore = 1): list<MatchResult> | All matches sorted by score descending, then by candidate ascending. limit: 0 yields none, and a negative limit is unlimited. |
| FuzzyMatcher | matchAllGenerator(string $query, iterable $candidates, ?int $limit = null, int $minScore = 1): \Generator | Yields the same ranked results. It drains and sorts the whole input before the first yield, because ranking is global. |
| MatchResult | $score / $needle / $haystack / $matchedIndices (readonly) | The match quality, the query, the candidate and the matched code-point offsets. |
| MatchResult | indices(): list<int> / isMatched(): bool / isEmpty(): bool | Matched offsets, score > 0, and no matched offsets. |
| SmithWatermanMatcher | new(?ScoringProfile $profile = null, int $maxQueryLength = 128, int $maxCandidateLength = 1000, bool $requireFullQuery = false) / forFiltering() | Local alignment. forFiltering() is full-query mode with the defaults. |
| SmithWatermanMatcher | withRequireFullQuery(bool) / withProfile() / withMaxQueryLength() / withMaxCandidateLength() | Immutable copies with one setting replaced. |
| SmithWatermanMatcher | profile() / maxQueryLength() / maxCandidateLength() / requiresFullQuery() | The configuration in effect. |
| SahilmMatcher | new(bool $caseSensitive = false, ?SahilmScoring $scoring = null) | Separator and camelCase bonus matcher. Requires the whole query to land. |
| SahilmMatcher | withCaseSensitive(bool) / withScoring(SahilmScoring) / caseSensitive() / scoring() | Immutable copies, and the configuration in effect. |
| ScoringProfile | canonical() / strict() / lenient() / new(...) | Smith-Waterman weight presets. new() takes named weights and keeps the canonical value for each one you omit. |
| ScoringProfile | withMatchScore() / withMismatchPenalty() / withGapOpen() / withGapExtend() / withAdjacentBonus() | Immutable weight setters. Every weight is an int. |
| SahilmScoring | canonical() / new(...) / withMatchScore() / withConsecutiveBonus() / withSeparatorBonus() / withCamelBonus() / withFirstCharBonus() / withLowerCaseBonus() | Immutable Sahilm weights. Canonical values are 1, 5, 10, 10, 15 and 1. |
| FuzzyMatcherFactory | named(string $type, ScoringProfile|SahilmScoring|null $scoring = null, bool $requireFullQuery = false, ?int $maxQueryLength = null, ?int $maxCandidateLength = null, bool $caseSensitive = false): FuzzyMatcher | 'smith-waterman' or 'sahilm'. A weight type that does not belong to the named matcher, or an unknown name, throws InvalidArgumentException. The requireFullQuery, maxQueryLength and maxCandidateLength options are 'smith-waterman' only. caseSensitive is 'sahilm' only, so caseSensitive: true with 'smith-waterman' throws, because that matcher folds case through CharFold. Passing one of these options to the wrong matcher also throws. |
| Highlighter | highlight(MatchResult $result, callable $styler): string / segments(MatchResult $result): list | Applies the styler to each matched run. segments() returns the runs that highlight() styles. |
| MatchResultSorter | sort(array $results) / sortAndSlice(array $results, ?int $limit) | The ranking behind matchAll(), public for callers who rank their own MatchResult lists. |
| CharFold | foldSplit(string): list<string> / fold(string): string | Per-codepoint case fold that stays 1:1 with the original string. Matched indices remain correct where a whole-string lowercase would expand, as with U+0130 and the final sigma. |
Options
Every matcher is configured through its constructor or factory, and every setter returns a new instance.
| Weight | canonical (default) | strict | lenient |
|---|---|---|---|
matchScore | 3 | 4 | 2 |
mismatchPenalty | −3 | −4 | −2 |
gapOpen | −5 | −6 | −3 |
gapExtend | −1 | −2 | −1 |
adjacentBonus | 5 | 6 | 3 |
| Setting | Default | Effect |
|---|---|---|
maxQueryLength | 128 | Only the first 128 query characters take part in an alignment. Under full-query mode, a longer query never matches. |
maxCandidateLength | 1000 | Only the first 1000 candidate characters are searched. A match that lies beyond the cap is missed. |
requireFullQuery | off | Every query character must land, in order. The best alignment is forced to cover them all, and the score floors at 1. |
SahilmMatcher caps | none | Sahilm is a single linear pass and is uncapped. Bound hostile-size candidates in the host. |
Over-cap input is truncated, never handed to a different algorithm, so the reported indices stay valid in the original candidate. The Smith-Waterman traceback costs about 1 KB per query row at the 1000-character candidate cap, which comes to about 128 KB at the default caps.
API reference
Every public class, interface, trait and enum under src/, grouped by namespace, with its method table. The listing is generated from the source PHPDoc; types and methods marked @internal are left out.
Only methods declared in sugar-fuzzy/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.
SugarCraft\Fuzzy
FuzzyMatcher interface
Fuzzy substring matcher — implementations score via Smith-Waterman local alignment (\SugarCraft\Fuzzy\Matcher\SmithWatermanMatcher) or greedy first-occurrence Sahilm matching (\SugarCraft\Fuzzy\Matcher\SahilmMatcher).
| Method | Summary |
|---|---|
match(string $query, string $candidate): ?MatchResult | Match a single candidate against the query. |
score(string $query, string $candidate): int | Score a single candidate WITHOUT (necessarily) building matched indices. |
matchAll(string $query, iterable $candidates, ?int $limit = null, int $minScore = 1): array | Match a query against an iterable of candidates, returning ranked results. |
matchAllGenerator(string $query, iterable $candidates, ?int $limit = null, int $minScore = 1): \Generator | Match a query against an iterable of candidates, yielding ranked results. |
Highlighter final class
Highlights matched character runs in a candidate string using a styler callable.
| Method | Summary |
|---|---|
highlight(MatchResult $result, callable $styler): string | Highlight matched runs in a candidate string. |
segments(MatchResult $result): array | Split the candidate into presentation-neutral matched/unmatched segments. |
MatchResult final class
Readonly result of a fuzzy match operation.
| Method | Summary |
|---|---|
__construct(public readonly string $needle, public readonly string $haystack, public readonly int $score, public readonly array $matchedIndices, public readonly int|string|null $candidateKey = null) | |
isEmpty(): bool | Whether the match is empty (no characters matched). |
isMatched(): bool | Whether this result represents a valid match (score > 0). |
indices(): array |
MatchResultSorter final class
Utility for sorting MatchResult collections.
| Method | Summary |
|---|---|
static sort(array $results): array | Sort by score descending, then haystack ascending as tiebreak. |
static sortAndSlice(array $results, ?int $limit): array | Sort and slice to limit. |
SahilmScoring final class
Scoring weights for the sahilm/fuzzy-style \SugarCraft\Fuzzy\Matcher\SahilmMatcher.
| Method | Summary |
|---|---|
__construct(public readonly int $matchScore = 1, public readonly int $consecutiveBonus = 5, public readonly int $separatorBonus = 10, public readonly int $camelBonus = 10, public readonly int $firstCharBonus = 15, public readonly int $lowerCaseBonus = 1) | |
static new(mixed ...$arguments): self | Root factory (repo convention). Forwards every argument, positional or named, so the constructor defaults stay the single source of the canonical weights. |
static canonical(): self | This port's historical weights — the SahilmMatcher default. |
withMatchScore(int $matchScore): self | |
withConsecutiveBonus(int $consecutiveBonus): self | |
withSeparatorBonus(int $separatorBonus): self | |
withCamelBonus(int $camelBonus): self | |
withFirstCharBonus(int $firstCharBonus): self | |
withLowerCaseBonus(int $lowerCaseBonus): self |
ScoringProfile final class
Scoring constants for the Smith-Waterman fuzzy matcher.
| Method | Summary |
|---|---|
__construct(public readonly int $matchScore = 3, public readonly int $mismatchPenalty = -3, public readonly int $gapOpen = -5, public readonly int $gapExtend = -1, public readonly int $adjacentBonus = 5) | |
static new(mixed ...$arguments): self | Root factory (repo convention). Equivalent to the constructor. |
static canonical(): self | Canonical SugarCraft scores. Bit-equivalent to the pre-SSOT hard-coded constants — the SmithWatermanMatcher default profile. A named preset alongside self::strict() / self::lenient(). |
static strict(): self | Tighter matching — higher rewards, harsher penalties. |
static lenient(): self | Lenient matching — lower rewards, gentler penalties. |
withMatchScore(int $matchScore): self | |
withMismatchPenalty(int $mismatchPenalty): self | |
withGapOpen(int $gapOpen): self | |
withGapExtend(int $gapExtend): self | |
withAdjacentBonus(int $adjacentBonus): self |
SugarCraft\Fuzzy\Matcher
CharFold final class
Per-codepoint lowercase folding that stays 1:1 with the original string.
| Method | Summary |
|---|---|
static foldSplit(string $string): array | Split a UTF-8 string and lowercase each code point individually. |
static fold(string $char): string | Lowercase a single code point. The result may be multi-code-point (U+0130 İ → i + U+0307) — callers must compare whole elements, never re-split the fold. |
FuzzyMatcherFactory final class
Factory for creating FuzzyMatcher instances by name.
| Method | Summary |
|---|---|
static named(string $type, ScoringProfile|SahilmScoring|null $scoring = null, bool $requireFullQuery = false, ?int $maxQueryLength = null, ?int $maxCandidateLength = null, bool $caseSensitive = false): FuzzyMatcher | Create a matcher by name. |
SahilmMatcher final class
Sahilm/fuzzy-style fuzzy matcher.
| Method | Summary |
|---|---|
__construct(bool $caseSensitive = false, ?SahilmScoring $scoring = null) | |
static new(bool $caseSensitive = false, ?SahilmScoring $scoring = null): self | Named constructor (repo convention); same options as the constructor. |
caseSensitive(): bool | Whether matching compares the original case. |
scoring(): SahilmScoring | The bonus weights in effect. |
withCaseSensitive(bool $caseSensitive = true): self | Copy of this matcher with case sensitivity switched (finding sugar-fuzzy-022: tuning a matcher meant rebuilding it). |
withScoring(SahilmScoring $scoring): self | Copy of this matcher using $scoring for the bonus weights. |
match(string $query, string $candidate): ?MatchResult | Match a single candidate against the query. |
score(string $query, string $candidate): int | Score a candidate through the interface door (finding sugar-fuzzy-033). |
matchAll(string $query, iterable $candidates, ?int $limit = null, int $minScore = 1): array | Match a query against an iterable of candidates, returning ranked results. |
matchAllGenerator(string $query, iterable $candidates, ?int $limit = null, int $minScore = 1): \Generator | Match a query against an iterable of candidates, yielding ranked results. |
SmithWatermanMatcher final class
Smith-Waterman-style local alignment fuzzy matcher.
| Method | Summary |
|---|---|
__construct(?ScoringProfile $profile = null, private readonly int $maxQueryLength = self::DEFAULT_MAX_QUERY_LENGTH, private readonly int $maxCandidateLength = self::DEFAULT_MAX_CANDIDATE_LENGTH, private readonly bool $requireFullQuery = false) | |
static new(?ScoringProfile $profile = null, int $maxQueryLength = self::DEFAULT_MAX_QUERY_LENGTH, int $maxCandidateLength = self::DEFAULT_MAX_CANDIDATE_LENGTH, bool $requireFullQuery = false): self | Named constructor (repo convention). Accepts every constructor option, with the same defaults, so callers never have to drop to new self(...) to tune the DoS caps or the full-query mode. |
static forFiltering(): self | The canonical filtering preset (FUZZY-13 leg b, finding sugar-fuzzy-007): local alignment scores partial hits, so a filter box would list candidates matching only a scattered subsequence; requireFullQuery keeps candidates whose alignment covers the WHOLE query — the shape command palettes want. Proof of demand: candy-code reaches this same construction from six sites (Commands/CommandRegistry.php:427, Chat.php:18606, Settings/SettingsSearch.php:68, Tui/SessionPicker.php:422, Attachments/MentionIndex.php:278 + :444 — cited as evidence only, no cross-lib edits here). Reachable both ways: new SmithWatermanMatcher( requireFullQuery: true), FuzzyMatcherFactory::named('smith-waterman', requireFullQuery: true) and this preset are the same matcher. |
profile(): ScoringProfile | The scoring profile in effect. |
maxQueryLength(): int | Query characters that take part in the alignment. |
maxCandidateLength(): int | Candidate characters (a prefix) that take part in the alignment. |
requiresFullQuery(): bool | Whether only alignments covering every query character count as matches. |
withRequireFullQuery(bool $require = true): self | Copy of this matcher with full-query coverage required (or not). |
withProfile(ScoringProfile $profile): self | Copy of this matcher using $profile for scoring (finding sugar-fuzzy-022: tuning a matcher meant rebuilding it through the constructor). |
withMaxQueryLength(int $limit): self | Copy of this matcher with a new query DoS cap. |
withMaxCandidateLength(int $limit): self | Copy of this matcher with a new candidate DoS cap. |
match(string $query, string $candidate): ?MatchResult | Match a single candidate against the query. |
score(string $query, string $candidate): int | Score a candidate WITHOUT building the traceback. |
matchAll(string $query, iterable $candidates, ?int $limit = null, int $minScore = 1): array | Match a query against an iterable of candidates, returning ranked results. |
matchAllGenerator(string $query, iterable $candidates, ?int $limit = null, int $minScore = 1): \Generator | Match a query against an iterable of candidates, yielding ranked results. |
Styling and highlighting
Highlighter takes a styler callable. It wraps each matched run in whatever the caller returns, and it returns unmatched text unchanged. The highlighter emits no color of its own. Pair any color with a bold or underline cue, so that color-blind users still see the match. Expose matchedIndices and the deterministic matchAll() order to non-visual channels, such as a screen reader.
Sanitizing is the caller's job. The highlighter forwards unmatched text verbatim, and the styler receives raw matched substrings. Strip \x1b and other control bytes before display. Case folding maps malformed UTF-8 bytes to ?, so a literal ? in the query can match untrusted text. Validate UTF-8 on both sides when the input is hostile.
Examples
examples/rank-matches.phpranks candidates for two queries and highlights each match with brackets, the way a TUI would style it.examples/full-query-picker.phpcompares local alignment with a full-query picker on the same input.examples/sahilm-paths.phpranks file paths with the Sahilm matcher, selected by name through the factory.
php examples/rank-matches.php
php examples/full-query-picker.php
php examples/sahilm-paths.php
Testing
composer install
vendor/bin/phpunit
The suite pins the scores of both algorithms against characterization tests. It also covers the full-query mode, the length caps, the Unicode case folding and the sorter's tie order.
Troubleshooting and FAQ
A query that should match returns null in Sahilm
Sahilm needs every query character to appear in order. A query such as ctf against a path with no such ordered subsequence is refused, even if local alignment would accept part of it. Use SmithWatermanMatcher when partial hits should score.
Swapping matchers changes the result set
Both matchers implement FuzzyMatcher, but they do not agree. Local alignment accepts partial queries, and Sahilm does not. A swap at a call site therefore turns a scored partial hit into null. Check the behavior you need before you swap.
A long candidate misses a match near its end
The candidate cap is 1000 characters by default, and the search stops there. Raise maxCandidateLength if the text is trusted and long. Sahilm is uncapped, so it finds the match, though the input is then unbounded.
Scores differ from another version
The canonical Smith-Waterman profile matches the old sugar-forms scores for ASCII input. Two documented deviations exist. An empty candidate scores 0 here, where the old sugar-forms shim scored it negative. Case folding works one code point at a time, so U+0130 and final sigma keep their indices.
Highlighted text shows escape sequences
The styler's output is inserted as is, so a raw candidate that contains \x1b injects its own codes. Sanitize the candidate before you match it, or before you display it.
Upstream mapping
Sahilm follows the bonus model of sahilm/fuzzy, a Go matcher. The shape of the scoring is shared, but the weight values are this port's own, pinned by the characterization suites. Smith-Waterman is the port of the sugar-forms core, and it has no Go counterpart.
| SugarCraft class | Upstream or origin | Notes |
|---|---|---|
SahilmMatcher, SahilmScoring | sahilm/fuzzy scoring shape | Separator, camelCase and first-character bonuses. The values are this port's own. |
SmithWatermanMatcher, ScoringProfile | sugar-forms FuzzyMatcher | Bit-equivalent for ASCII input within the default caps. |
CharFold | original | Per-codepoint case folding that keeps indices exact. |
Architecture
The matchers do no I/O and hold no state beyond their configuration. Each MatchResult is an immutable value. matchAll() scores every candidate, then hands the survivors to MatchResultSorter, which applies the ranking and the limit. The generator form buffers everything, because the ranking needs the full set. CharFold sits under both matchers, so the indices match the original string.
Changelog and versioning
The library is pre-1.0 and has no tagged releases yet, so consume dev-master. The scoring behavior is pinned by the test suite, so a change to the weights shows up as a failing characterization test.
Source
Related
- sugar-quickpick is the fuzzy finder overlay that uses the matched indices to paint each ranked row.
- sugar-forms and sugar-treelist keep back-compat shims over this library.