PHP Conference Japan 2024

quotemeta

(PHP 4, PHP 5, PHP 7, PHP 8)

quotemeta將特殊字元加上反斜線跳脫

說明

quotemeta(字串 $string): 字串

會回傳一個字串版本,其中在以下這些字元之前都加上一個反斜線字元 (\): . \ + * ? [ ^ ] ( $ )

. \ + * ? [ ^ ] ( $ )

參數

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\."

注意事項

注意: 此函式是二進位安全的。

參見

新增註釋

使用者貢獻的註釋 3 則註釋

kumarkulandai at gmail dot com
15 年前
<?php
$str
= "Hello world. (can you hear me?)";
echo
quotemeta($str);
?>

以上程式碼的輸出結果為
Hello world\. \(can you hear me\?\)
George Adams
18 年前
我花了一段時間才意識到,這並不是我想要用來跳脫字串中潛在有害字元的指令,該字串將被用作系統指令的一部分。 相反地,我需要 escapeshellarg() (https://php.dev.org.tw/manual/en/function.escapeshellarg.php) 或 escapeshellcmd() (https://php.dev.org.tw/manual/en/function.escapeshellcmd.php)
匿名
23 年前
這個函式會跳脫在正規表達式中具有特殊含義的字元。 preg_quote() <https://php.dev.org.tw/manual/en/function.preg-quote.php> 具有類似的功能,但功能更強大,因为它可以跳脫更多字元(包括一個使用者指定的字元)。
To Top