Files
breadcrumb-the-shire/lib/Support/Search/SearchQueryNormalizer.php

41 lines
1.1 KiB
PHP
Raw Normal View History

<?php
namespace MintyPHP\Support\Search;
class SearchQueryNormalizer
{
2026-03-06 00:44:52 +01:00
// Prepares a user query for SQL LIKE. Escapes \ and _ (LIKE special chars),
// converts * to %, and wraps with % wildcards if not already present.
public static function normalizeLikeQuery(string $query): string
{
$query = trim($query);
if ($query === '') {
return '';
}
$query = str_replace('\\', '\\\\', $query);
$query = str_replace('_', '\\_', $query);
$query = str_replace('*', '%', $query);
if (!str_starts_with($query, '%')) {
$query = '%' . $query;
}
if (!str_ends_with($query, '%')) {
$query .= '%';
}
return $query;
}
2026-03-06 00:44:52 +01:00
// Strips wildcard chars for relevance scoring — score queries need a clean term, not a LIKE pattern.
public static function normalizeScoreQuery(string $query): string
{
$query = trim($query);
if ($query === '') {
return '';
}
return str_replace(['*', '%', '_'], '', $query);
}
}