PHP - addslashes() 函式



PHP 的 addslashes() 函式用於轉義特殊字元,例如單引號 (''), 雙引號 (""), 反斜槓 (\\), 和 NULL 字元 (\0)。

此函式返回轉義後的字串(帶引號的字串),在需要轉義的特殊字元前新增反斜槓。

要轉義給定字串中的特定字元,PHP 提供了另一個名為 addcslashes() 函式。

語法

以下是 PHP addslashes() 函式的語法:

addslashes(string $str): string

引數

此函式接受一個引數,如下所述:

  • str - 需要轉義的字串。

返回值

此函式返回轉義後的字串。

示例 1

從字串中轉義單引號 (') 特殊字元。

以下是 PHP addslashes() 函式的基本示例:

<?php
   $str = "Tutorials'point";
   echo "The given string is: $str";
   #using addslashes() function
   echo "\nThe escaped string: ".addslashes($str);
?>

輸出

以上程式輸出如下:

The given string is: Tutorials'point
The escaped string: Tutorials\'point

示例 2

從字串中轉義雙引號 (") 特殊字元。

以下是 PHP addslashes() 函式的另一個示例。我們使用此函式透過跳脫字元串 'Welcome to "Tutorialspoint"' 中的所有雙引號 (") 字元來檢索轉義後的字串:

<?php
   $str = 'Welcome to "Tutorialspoint"';
   echo "The given string is: $str";
   #using addslashes() function
   echo "\nThe escaped string: ".addslashes($str);
?>

輸出

執行以上程式後,將顯示以下輸出:

The given string is: Welcome to "Tutorialspoint"
The escaped string: Welcome to \"Tutorialspoint\"

示例 3

從字串中轉義 NULL 字元 (\0)

以下是如何使用 PHP addslashes() 函式從字串中轉義 NULL 字元的示例:

<?php
   $str = "Hello World\0";
   echo "The given string is: $str";
   #using addslashes() function
   echo "\nThe escaped string: ".addslashes($str);
?>

輸出

執行以上程式後,將生成以下輸出:

The given string is: Hello World
The escaped string: Hello World\0
php_function_reference.htm
廣告