首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> MySQL 資料庫 >> MySQL 綜合教學

MySQL 通配符查詢實現:將 * 轉換為 % 實現 LIKE 模糊匹配的 PHP 方案

     編輯:MySQL 綜合教學

前端輸入通配符 *(如 sun*、*zhong*、sun*zhong*),後端需轉換為 MySQL LIKE 模式的 %。本文提供一個健壯的 PHP 處理函數,支持多段通配符、去除首尾多餘 %、空段過濾。

轉換規則映射

用戶輸入轉換後 LIKE 模式含義
sunzhongshansunzhongshan精確匹配
sun*sun%以 sun 開頭
*shan%shan以 shan 結尾
sun*shansun%shan%以 sun 開頭、以 shan 結尾
*zhong*%zhong%包含 zhong
sun*zhong*sun%zhong%以 sun 開頭、包含 zhong

核心轉換邏輯(PHP)

function buildLikeConditions(string $input, string $column = 'username'): string {
    // 1. * 替換為 %,%
    $step1 = str_replace('*', '%,%', $input);
    // 2. 去除首尾多餘 %
    $step2 = trim($step1, '%');
    // 3. 按逗號分割
    $parts = explode(',', $step2);
    // 4. 過濾空段並構建 LIKE 條件
    $conditions = [];
    foreach ($parts as $part) {
        $part = trim($part);
        if ($part === '') continue;
        $conditions[] = "`$column` LIKE '$part'";
    }
    // 5. 組合 SQL 片段
    return $conditions ? ' AND ' . implode(' AND ', $conditions) : '';
}

// 使用示例
$sql = "SELECT autoid FROM users WHERE 1=1";
$sql .= buildLikeConditions('sun*zhong*');
echo $sql;
// 輸出:SELECT autoid FROM users WHERE 1=1 AND `username` LIKE 'sun%' AND `username` LIKE '%zhong%'

關鍵點解析

  1. str_replace('*', '%,%'):將單個 * 展開為 %,%,使得 sun*zhong → sun%,%zhong,分割後得到 sun% 和 %zhong。
  2. trim($str, '%'):移除首尾可能產生的多餘 %(如 *abc → %,%abc → %abc)。
  3. explode(','):按逗號分割為多段模式。
  4. 多條件 AND 連接:等價於 LIKE 'sun%' AND LIKE '%zhong%',邏輯上為「同時滿足所有片段」,符合通配符語義。

安全加固:防止 SQL 注入

生產環境**務必使用預處理語句**:

$stmt = $pdo->prepare("SELECT autoid FROM users WHERE 1=1" . buildLikeConditions($input, '?'));
// buildLikeConditions 需改造為返回佔位符數組,並綁定參數
// 簡易版:手動構建佔位符
$parts = array_filter(explode(',', trim(str_replace('*', '%,%', $input), '%')));
$placeholders = implode(' AND ', array_fill(0, count($parts), "`username` LIKE ?"));
$stmt = $pdo->prepare("SELECT autoid FROM users WHERE 1=1 AND $placeholders");
$stmt->execute($parts);

擴展:支持轉義字面 % 和 _

若用戶需搜索字面 % 或 _,可約定轉義字符(如 \%、\_),在構建模式前替換:

$input = str_replace(['\%', '\_'], ['\\%', '\\_'], $input); // 保留給 LIKE 的轉義

此方案簡潔、無依賴、易維護,適合中小項目快速接入通配符搜索。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved