PHP 內建函數超過 1000 個,記憶不切實際,善用「分類索引 + 高頻核心」才是高效開發關鍵。本文將官方函數庫按功能域重新組織,標註高頻必會函數、常見誤區、PHP 7/8 現代替代方案,並提供可離線查閱的結構化速查表。
| 大類 | 子分類 | 代表函數 | 高頻標記 |
|---|---|---|---|
| 字串 | 大小寫/修飾 | strtolower, strtoupper, ucfirst, ucwords, trim, ltrim, rtrim | ⭐⭐⭐ |
| 查找/比較 | strpos, stripos, strrpos, strripos, strcmp, strcasecmp, strnatcmp, similar_text | ⭐⭐⭐ | |
| 截取/替換/分割 | substr, substr_replace, str_replace, str_ireplace, explode, implode, str_split, preg_split | ⭐⭐⭐ | |
| 編碼/雜湊/格式化 | md5, sha1, hash, password_hash, password_verify, base64_encode, json_encode, sprintf, number_format | ⭐⭐⭐ | |
| 陣列 | 建立/合併/分割 | array, array_merge, array_merge_recursive, array_combine, array_chunk, array_slice, array_splice | ⭐⭐⭐ |
| 查找/過濾/排序 | in_array, array_search, array_keys, array_values, array_filter, array_map, array_reduce, array_unique, sort, rsort, asort, ksort, usort, natsort | ⭐⭐⭐ | |
| 指標/堆疊/隊列 | current, next, prev, reset, end, each, key, array_push, array_pop, array_shift, array_unshift | ⭐⭐ | |
| 檔案系統 | 讀寫/指標 | fopen, fclose, fread, fwrite, fgets, fgetcsv, file_get_contents, file_put_contents, file, readfile | ⭐⭐⭐ |
| 資訊/權限/時間 | file_exists, is_file, is_dir, is_readable, is_writable, filesize, filemtime, filectime, stat, realpath, pathinfo | ⭐⭐⭐ | |
| 目錄/掃描/臨時 | opendir, readdir, scandir, glob, mkdir, rmdir, tempnam, tmpfile, symlink, readlink | ⭐⭐ | |
| 日期時間 | 格式化/解析 | date, time, strtotime, mktime, microtime, strftime, gmdate, date_create, DateTime::format | ⭐⭐⭐ |
| 時區/間隔/運算 | date_default_timezone_set, DateTimeZone, DateInterval, DatePeriod, date_diff, date_add, date_sub | ⭐⭐⭐ | |
| 曆法/轉換 | checkdate, cal_days_in_month, easter_date, jdtogregorian, gregoriantojd | ⭐ | |
| 資料庫 (MySQL) | mysqli (推薦) | mysqli_connect, mysqli_query, mysqli_prepare, mysqli_stmt_bind_param, mysqli_fetch_assoc, mysqli_affected_rows | ⭐⭐⭐ |
| PDO (通用) | PDO::__construct, prepare, execute, fetch, fetchAll, lastInsertId, beginTransaction, commit, rollBack | ⭐⭐⭐ | |
| XML/JSON | XML | simplexml_load_string, simplexml_load_file, DOMDocument, DOMXPath, XMLReader, XMLWriter | ⭐⭐⭐ |
| JSON | json_encode, json_decode, json_last_error, json_last_error_msg, JsonSerializable | ⭐⭐⭐ | |
| 網路/通訊 | HTTP/URL | file_get_contents (stream), cURL (curl_init, curl_setopt, curl_exec), parse_url, http_build_query, get_headers | ⭐⭐⭐ |
| 郵件/FTP/Socket | mail, imap_open, fsockopen, stream_socket_client, ftp_connect, ftp_put, ftp_get | ⭐⭐ | |
| 安全/加密 | 密碼/雜湊 | password_hash, password_verify, password_needs_rehash, hash_hmac, hash_equals, random_bytes, random_int | ⭐⭐⭐ |
| 加密/解密 | openssl_encrypt, openssl_decrypt, openssl_sign, openssl_verify, sodium_crypto_* (PHP 7.2+) | ⭐⭐⭐ | |
| 錯誤/除錯 | 處理/日誌/回溯 | error_reporting, set_error_handler, set_exception_handler, error_log, debug_backtrace, debug_print_backtrace, trigger_error | ⭐⭐⭐ |
| 執行/效能 | 緩存/睡眠/記憶體 | sleep, usleep, time_nanosleep, memory_get_usage, memory_get_peak_usage, gc_collect_cycles, opcache_* | ⭐⭐ |
| 反射/類別 | 檢測/實例化/屬性 | class_exists, interface_exists, trait_exists, get_class, get_parent_class, ReflectionClass, instanceof, ::class | ⭐⭐ |
| 舊函數/寫法 | 問題 | 現代替代 (PHP 7/8+) | 版本 |
|---|---|---|---|
| mysql_* 系列 | PHP 7.0 移除、無預處理、SQL 注入高風險 | mysqli / PDO | 5.0 / 5.1 |
| ereg / eregi / split | POSIX 正則引擎,PHP 7.0 移除 | preg_* (PCRE) | 5.3 |
| each() | PHP 7.2 棄用,8.0 移除 | foreach / array_keys + array_values | 7.2 |
| create_function() | eval 風險、效能差、PHP 7.2 棄用,8.0 移除 | 匿名函數 fn() / function() | 5.3 |
| md5() / sha1() 存密碼 | 極快、無鹽、彩虹表秒破 | password_hash() / password_verify() | 5.5 |
| rand() / mt_rand() 產生 Token | 非加密安全、可預測 | random_bytes() / random_int() / bin2hex() | 7.0 |
| json_encode() 無選項 | 中文 Unicode 轉義、斜線轉義、數字當字串 | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK | 5.4 |
| date() / strtotime() 處理時區 | 易混淆、夏令時 Bug、無物件導向 | DateTime / DateTimeImmutable / DateTimeZone | 5.2 |
| serialize() / unserialize() | 物件注入風險、跨語言不相容 | JSON / igbinary / msgpack / protobuf | - |
| $_GET/$_POST 直接用 | XSS、CSRF、型別不安全 | filter_input() / filter_var() / 表單請求類 / Validator | 5.2 |
| include/require 變數路徑 | 目錄遍歷、遠程代碼執行 (RFI/LFI) | 自動載入 (Composer PSR-4) / 白名單路徑 | 5.3 |
| extract() / compact() | 變數污染、作用域混亂、難以靜態分析 | 明確陣列/物件傳遞 | - |
| @ 抑制錯誤 | 隱藏 Bug、效能損耗、難以除錯 | try-catch / 條件判斷 / 自訂錯誤處理器 | - |
<?php
// 1. 安全截取 UTF-8 字串 (mbstring)
function mbTruncate(string $str, int $length, string $suffix = '...'): string
{
if (mb_strlen($str) <= $length) return $str;
return mb_substr($str, 0, $length) . $suffix;
}
// 2. 靈活分割:多字元分隔符 + 過濾空值
$tags = array_filter(array_map('trim', preg_split('/[,,;;\s|]+/', $input)));
// 3. 模板替換:陣列鍵值對應
$template = 'Hello {name}, your order {id} is {status}.';
$data = ['name' => 'John', 'id' => 'A123', 'status' => 'shipped'];
echo strtr($template, $data); // 最快、單次遍歷、不重複替換
// 4. 安全輸出 HTML
echo htmlspecialchars($userInput, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
// 或使用現代模板引擎自動逃逸
// 5. 密碼驗證常數時間比較 (防時序攻擊)
if (hash_equals($expectedHash, $providedHash)) { /* ... */ }
?>
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'age' => 28, 'roles' => ['admin']],
['id' => 2, 'name' => 'Bob', 'age' => 35, 'roles' => ['editor']],
['id' => 3, 'name' => 'Charlie', 'age' => 22, 'roles' => ['viewer']],
];
// 篩選 + 映射 + 索引重建 (鏈式,PHP 7.4+ 箭頭函數)
$adultAdmins = array_values(array_filter($users, fn($u) => $u['age'] >= 18 && in_array('admin', $u['roles'])));
// 分組索引:按角色分組
$byRole = [];
foreach ($users as $u) {
foreach ($u['roles'] as $role) {
$byRole[$role][] = $u['name'];
}
}
// 唯一值統計
$roleCounts = array_count_values(array_merge(...array_column($users, 'roles')));
// 多鍵排序:年齡降冪、名稱升冪
array_multisort(
array_column($users, 'age'), SORT_DESC,
array_column($users, 'name'), SORT_ASC,
$users
);
// 記憶體友善:大陣列分塊處理
function chunkProcess(array $data, int $size, callable $fn): void
{
foreach (array_chunk($data, $size, true) as $chunk) {
$fn($chunk);
unset($chunk); // 及時釋放
}
}
?>
<?php
// 1. 讀取大檔案:生成器逐行 (記憶體常數)
function readLines(string $path): Generator
{
$fp = fopen($path, 'r');
try {
while (($line = fgets($fp)) !== false) {
yield rtrim($line, "\r\n");
}
} finally {
fclose($fp);
}
}
foreach (readLines('huge.log') as $line) {
if (str_contains($line, 'ERROR')) { /* ... */ }
}
// 2. 原子寫入:臨時檔 + rename (防止部分寫入被讀取)
function atomicPut(string $path, string $data): void
{
$tmp = $path . '.tmp.' . bin2hex(random_bytes(8));
file_put_contents($tmp, $data);
rename($tmp, $path); // 同檔案系統下原子
}
// 3. CSV 標準讀寫
function readCsv(string $path): Generator
{
$fp = fopen($path, 'r');
$header = fgetcsv($fp);
while (($row = fgetcsv($fp)) !== false) {
yield array_combine($header, $row);
}
fclose($fp);
}
function writeCsv(string $path, iterable $rows, array $header): void
{
$fp = fopen($path, 'w');
fputcsv($fp, $header);
foreach ($rows as $row) {
fputcsv($fp, array_intersect_key($row, array_flip($header)));
}
fclose($fp);
}
?>
str_contains, str_starts_with, array_is_list, fsync 等)函數是 PHP 的詞彙,框架是語法,架構是文章。詞彙貧乏,寫不出好文章。從今天開始,每天掌握一個新函數的現代用法。