PHP - addcslashes() 函式



PHP 的 addcslashes() 函式用於檢索跳脫字元串,在字元引數中列出的字元前面新增反斜槓。

“轉義”字串是指使用轉義序列(以反斜槓 \ 開頭)來表示特殊字元的字串。例如,\n 表示換行符,\" 表示引號。

此函式接受一個引數作為字元列表。如果字元列表包含 '\n'、'\r' 等字元,則它們將以“C 風格”進行轉換。此外,任何 ASCII 程式碼低於“32”且高於“126”的非字母數字字元都將轉換為八進位制表示。

語法

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

addcslashes(string $str, string $characters): string

引數

此函式接受以下兩個引數:

  • str − 要轉義的字串。
  • characters − 要轉義的字元列表。

返回值

此函式返回一個跳脫字元串。

示例 1

跳脫字元串中的特定字元。

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

<?php
   $str = "Tutorialspoint";
   echo "The given string is: $str";
   $chars = "ia";
   echo "\nThe give list of chars: $chars";
   #using addcslashes() function
   echo "\nThe escaped string: ".addcslashes($str, $chars);
?>

輸出

上述程式輸出如下:

The given string is: Tutorialspoint
The give list of chars: ia
The escaped string: Tutor\i\alspo\int

示例 2

跳脫字元串中的所有大寫字母。

這是 PHP addcslashes() 函式的另一個示例。此函式用於透過跳脫字元串“Hello World”中的所有大寫字母來檢索跳脫字元串:

<?php
   $str = "Hello World";
   echo "The given string is: $str";
   #using addcslashes() function
   echo "\nThe escaped string: ".addcslashes($str, 'A..Z');
?>

輸出

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

The given string is: Hello World
The escaped string: \Hello \World

示例 3

跳脫字元串中的所有小寫字母和大寫字母。

在下面的示例中,我們使用此屬性來轉義返回字串中的所有小寫字母和大寫字母:

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

輸出

以下是上述程式的輸出:

The given string is: Welcome to [Tutorialspoint]
The escaped string: \W\e\l\c\o\m\e \t\o \[\T\u\t\o\r\i\a\l\s\p\o\i\n\t\]
php_function_reference.htm
廣告