整理常用字串函式行為與陷阱,包含 substr() 正負參數規則、explode() 進階用法、strrev() 反轉字串,以及 setlocale() 本地化設定。
substr(string, start, length)
$str = 'php is very good language';
substr($str, 4, 5); // 'is ve'
substr($str, -4, 5); // 'uage' (從倒數第 4 字元取 5 碼)
substr($str, 4, -5); // 'is very good lan' (排除尾端 5 碼)
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1 $data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo strrev("june"); // enuj
setlocale(category, locale)
LC_ALL (全部)、LC_CTYPE (字元分類/大小寫)、LC_TIME (日期時間格式)、LC_MONETARY (貨幣)、LC_NUMERIC (數值)、LC_COLLATE (排序)、LC_MESSAGES (系統訊息)。zh_TW.UTF-8、en_US.UTF-8、C (預設)。注意:setlocale() 影響程序全域,多執行緒環境 (如 PHP-FPM) 需謹慎使用,建議改用 NumberFormatter、IntlDateFormatter 等 Intl 擴充套件。