首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 字串整理處理:修剪空白、大小寫轉換、HTML/URL/SQL 轉義

     編輯:PHP 綜合知識

1. 單一字元存取

<?php
$str = 'Hello';
echo $str[0];  // 'H' (位元組存取)
echo $str{0};  // 同左 (舊語法,PHP 7.4 棄用)

// 多位元組字元需用 mb_substr
$zh = '中文';
echo mb_substr($zh, 0, 1, 'UTF-8'); // '中'
?>

2. 修剪空白字元

<?php
$str = "  \t\n  Hello \r\n ";

// 預設修剪:空格、Tab、換行、回車、Null、垂直定位鍵
echo trim($str);   // "Hello"
echo ltrim($str);  // "Hello \r\n "
echo rtrim($str);  // "  \t\n  Hello"

// 自訂字元清單
echo trim($str, " \t\n\r\0\x0BH"); // "ello" (也修剪 H)
?>

3. 大小寫轉換

<?php
$str = 'hello WORLD';

echo strtolower($str); // 'hello world'
echo strtoupper($str); // 'HELLO WORLD'
echo ucfirst($str);    // 'Hello WORLD' (首字元大寫)
echo ucwords($str);    // 'Hello World' (每單字首字元大寫)

// 多位元組版本
echo mb_strtolower($str, 'UTF-8');
echo mb_convert_case($str, MB_CASE_TITLE, 'UTF-8'); // ucwords 等效
?>

4. HTML 轉義 (防 XSS)

<?php
$html = ' & "quotes"';

// htmlentities: 所有可轉換字元 → 實體
echo htmlentities($html, ENT_QUOTES, 'UTF-8');
// <script>alert("XSS")</script> & "quotes"

// htmlspecialchars: 僅必要字元 (&, ", ', <, >)
echo htmlspecialchars($html, ENT_QUOTES, 'UTF-8');
// <script>alert("XSS")</script> & "quotes"

// 反轉義
echo html_entity_decode($encoded, ENT_QUOTES, 'UTF-8');
?>

5. URL 轉義

<?php
$url = 'https://example.com/search?q=中文&page=1';

// urlencode: 空格 → +,其他非英數 → %XX
echo urlencode($url);
// https%3A%2F%2Fexample.com%2Fsearch%3Fq%3D%E4%B8%AD%E6%96%87%26page%3D1

// urldecode: 反向
echo urldecode($encoded);

// rawurlencode: 空格 → %20 (RFC 3986 標準,建議用於路徑/參數值)
echo rawurlencode($url);
// https%3A%2F%2Fexample.com%2Fsearch%3Fq%3D%E4%B8%AD%E6%96%87%26page%3D1

// rawurldecode: 反向
?>

6. SQL 轉義 (防注入)

<?php
// 方案一:Prepared Statements (唯一推薦,PDO/MySQLi)
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);

// 方案二:舊式 addslashes (僅作為輸出顯示或極簡環境)
$escaped = addslashes($input);  // ' → \', " → \", \ → \\, NUL → \0
// 反向
$original = stripslashes($escaped);

// 注意:addslashes 不足以防禦所有注入 (編碼繞過、多字節字元),**嚴禁用於生產環境 SQL 拼接**。
?>

最佳實務總結

場景推薦函數禁用/慎用
HTML 輸出htmlspecialchars($str, ENT_QUOTES, 'UTF-8')htmlentities (過度轉換)、直接輸出
URL 參數值rawurlencode($val)urlencode (空格成 + 非標準)
SQL 查詢**Prepared Statements (PDO/MySQLi)**addslashes, mysql_real_escape_string (已移除)
Shell 指令escapeshellarg($arg), escapeshellcmd($cmd)直接拼接
JSON 輸出json_encode($data, JSON_UNESCAPED_UNICODE)手動拼接
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved