萬盛學電腦網

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

PHP 字串操作與正則表達式完全指南:格式化、比較、搜尋替換、分割與 PCRE 實戰

字串格式化與清理

<?php
// 去除空白
$str = "  Hello World  \n";
trim($str);       // "Hello World"
ltrim($str);      // "Hello World  \n"
rtrim($str);      // "  Hello World"
rtrim($str, "\n\r\t "); // 自定義字元集

// 大小寫轉換
strtolower('HELLO');     // hello
strtoupper('hello');     // HELLO
ucfirst('hello world');  // Hello world (首字母)
ucwords('hello world');  // Hello World (每單字首字母)
mb_strtoupper('中文');    // 多位元組安全版 (需 mbstring)

// printf / sprintf 格式化
$name = 'John'; $age = 30;
printf("Name: %s, Age: %d, Score: %.2f\n", $name, $age, 99.5);
// 輸出:Name: John, Age: 30, Score: 99.50
$formatted = sprintf("User: %s (%d)", $name, $age); // 回傳字串

// 轉義
addslashes("O'Reilly");     // O\'Reilly (單引號、雙引號、反斜線、NUL)
stripslashes("O\'Reilly");  // 還原
htmlspecialchars('
						
copyright © 萬盛學電腦網 all rights reserved