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

PHP 字串操作函式速查:substr()、explode()、strrev() 與 setlocale()

     編輯:PHP 相關知識

整理常用字串函式行為與陷阱,包含 substr() 正負參數規則、explode() 進階用法、strrev() 反轉字串,以及 setlocale() 本地化設定。

substr() — 截取子字串

substr(string, start, length)
  • start ≥ 0:從開頭第 start 個字元 (0 起算)。
  • start < 0:從結尾往前第 |start| 個字元 (從 -1 開始)。
  • length > 0:最多取 length 字元。
  • length < 0:從結尾往前排除 |length| 字元。
  • length = 0 或省略:取到字串結尾。
$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 碼)

explode() — 字串分割陣列

$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);

strrev() — 字串反轉

echo strrev("june"); // enuj

setlocale() — 設定地區環境

setlocale(category, locale)
  • category:LC_ALL (全部)、LC_CTYPE (字元分類/大小寫)、LC_TIME (日期時間格式)、LC_MONETARY (貨幣)、LC_NUMERIC (數值)、LC_COLLATE (排序)、LC_MESSAGES (系統訊息)。
  • locale:如 zh_TW.UTF-8、en_US.UTF-8、C (預設)。

注意:setlocale() 影響程序全域,多執行緒環境 (如 PHP-FPM) 需謹慎使用,建議改用 NumberFormatter、IntlDateFormatter 等 Intl 擴充套件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved