quotemeta(string $string): string 會在字符串中具有特殊正則含義的字符前自動插入反斜杠 (\),返回轉義後的新字符串。這在構建動態正則表達式、SQL 片段或 Shell 命令時極為實用,能防止元字符被誤解析。
.\+*?[]^$()quotemeta(string $string): string
參數:$string - 需要轉義的輸入字符串。
返回值:轉義後的字符串。
<?php
$str = "Hello world. (can you hear me?)";
echo quotemeta($str);
// 輸出:Hello world\. \(can you hear me\?\)
?>
$keyword = "user(name)?";
$pattern = '/^' . quotemeta($keyword) . '$/'; // 精確匹配字面量 "user(name)?"
$search = "100%";
$safe = quotemeta($search); // 100\%
$sql = "SELECT * FROM products WHERE name LIKE '%$safe%'";
若需還原,可用 stripslashes() 移除由 quotemeta() 或 addslashes() 添加的反斜杠。
$escaped = quotemeta($str);
$original = stripslashes($escaped);
quotemeta() 是 PHP 內建的輕量級字面量轉義工具,適合快速將用戶輸入或變量值安全嵌入正則、SQL LIKE、Shell 命令等上下文。記住它的轉義字符集固定且有限,複雜場景請改用專用轉義函數(如 preg_quote()、mysqli_real_escape_string()、escapeshellarg())。