萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP addcslashes() 與 stripcslashes() 函數完整用法指南

在 PHP 開發中,處理字串跳脫是常見需求。addcslashes() 與 stripcslashes() 是一組配套函數,分別用於在指定字元前加上反斜線跳脫,以及移除字串中的反斜線。本文將詳細說明這兩個函數的語法、參數與實際應用範例。

函數語法與參數說明

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

  • $str:待處理的原始字串
  • $charlist:指定需跳脫的字元清單,可使用範圍表示法(如 a..z)
  • 回傳值:在指定字元前加上反斜線後的字串

stripcslashes(string $str): string

  • $str:含有跳脫字元的字串
  • 回傳值:移除所有反斜線跳脫後的字串

實戰範例:SQL 語句跳脫處理

<?php
$sql = "update book set bookname='let's go' where bookid=1";
echo $sql . "<br>";
// 原始輸出:update book set bookname='let's go' where bookid=1

$new_sql = addcslashes($sql, "'");
echo $new_sql . "<br>";
// 跳脫後:update book set bookname=\'let\'s go\' where bookid=1

$new_sql_01 = stripcslashes($new_sql);
echo $new_sql_01;
// 還原後:update book set bookname='let's go' where bookid=1
?>

進階用法與注意事項

字元範圍指定: charlist 參數支援範圍寫法,例如 'A..Z' 會跳脫所有大寫字母,'\0..\37' 則跳脫所有控制字元。

常見跳脫字元:

  • \n - 換行符
  • \r - 回車符
  • \t - 定位符
  • \\ - 反斜線本身
💡 實務建議: 處理資料庫查詢時,建議優先使用 PDO 預備語句或 mysqli_real_escape_string(),而非手動跳脫。addcslashes() 較適合特定格式輸出(如 C 風格字串、正則模式)場景。

函數對比總結

函數用途典型應用場景
addcslashes() 在指定字元前加反斜線 產生 C/Perl 風格跳脫字串、正則模式預處理
stripcslashes() 移除反斜線跳脫 還原被 addcslashes() 處理過的字串
copyright © 萬盛學電腦網 all rights reserved