<?php
$str = "Hello world. (can you hear me?)";
echo quotemeta($str);
?>
以上程式碼的輸出結果為
Hello world\. \(can you hear me\?\)
(PHP 4, PHP 5, PHP 7, PHP 8)
quotemeta — 將特殊字元加上反斜線跳脫
會回傳一個字串版本,其中在以下這些字元之前都加上一個反斜線字元 (\
): . \ + * ? [ ^ ] ( $ )
string
輸入字串。
回傳加上跳脫字元後的字串,如果 string
給定的是空字串,則回傳 false
。
範例 #1 quotemeta() 範例
<?php
var_dump(quotemeta('PHP is a popular scripting language. Fast, flexible, and pragmatic.'));
?>
上述範例將輸出:
string(69) "PHP is a popular scripting language\. Fast, flexible, and pragmatic\."
注意: 此函式是二進位安全的。
<?php
$str = "Hello world. (can you hear me?)";
echo quotemeta($str);
?>
以上程式碼的輸出結果為
Hello world\. \(can you hear me\?\)
我花了一段時間才意識到,這並不是我想要用來跳脫字串中潛在有害字元的指令,該字串將被用作系統指令的一部分。 相反地,我需要 escapeshellarg() (https://php.dev.org.tw/manual/en/function.escapeshellarg.php) 或 escapeshellcmd() (https://php.dev.org.tw/manual/en/function.escapeshellcmd.php)
這個函式會跳脫在正規表達式中具有特殊含義的字元。 preg_quote() <https://php.dev.org.tw/manual/en/function.preg-quote.php> 具有類似的功能,但功能更強大,因为它可以跳脫更多字元(包括一個使用者指定的字元)。