熟練掌握核心內置函數,能讓業務代碼更簡潔、性能更優、Bug 更少。本文精選實戰中 使用頻率最高、最易踩坑 的日期、字符串、數組函數,附帶參數解析、實戰示例與避坑提示,建議收藏備查。
<?php
// 相對時間(極其強大)
strtotime('now'); // 當前時間戳
strtotime('+1 week'); // 一周後
strtotime('next Monday'); // 下周一
strtotime('last day of next month'); // 下月最後一天
// 固定格式
strtotime('2024-02-29 15:30:00'); // 指定日期
?>
避坑:strtotime('2024-02-30') 會自動修正為 3 月 1 日,業務若需嚴格校驗請用 DateTime::createFromFormat。
<?php
$ts = 1707456000; // 2024-02-09 12:00:00
date('Y-m-d H:i:s', $ts); // 2024-02-09 12:00:00
date('Y年m月d日 l', $ts); // 2024年02月09日 Friday
?>
常用格式字符:Y/m/d H:i:s / l(星期全寫) / D(縮寫) / t(月天數) / w(0-6 星期) / z(年內天數)。
<?php $str = 'Hello World'; substr($str, 6); // 'World' 從第 6 位到結尾 substr($str, 6, 5); // 'World' 長度 5 substr($str, -6); // 'World' 負數從末尾倒數 substr($str, 0, -6); // 'Hello' 排除末尾 6 位 ?>
中文截取:mb_substr($str, 0, 10, 'utf-8'),防止截斷多字節字符產生亂碼。
<?php $arr = [1, 2, 2, 3, 3, 3]; array_unique($arr); // [1, 2, 3] 鍵名保持 0,1,3 ?>
注意:嚴格模式比較(類型+值),[1, '1'] 視為不同;二維數組去重需配合 array_map('serialize', $arr) 技巧。
<?php
// 1. 刪除所有「假值」(0, '', null, false, [])
$entry = [0 => 'foo', 1 => false, 2 => -1, 3 => null, 4 => ''];
array_filter($entry); // [0 => 'foo', 2 => -1]
// 2. 自定義回調:保留奇數
$arr = ['a'=>1, 'b'=>2, 'c'=>3, 'd'=>4, 'e'=>5];
array_filter($arr, function($v){ return $v & 1; });
// ['a'=>1, 'c'=>3, 'e'=>5] 鍵名保留
?>
陷阱:0 和 '0' 會被當作 false 過濾掉,若需保留請顯式回調 fn($v) => $v !== '' && $v !== null。
<?php
function slugify($title)
{
// 1. 中文轉拼音(需引入 Pinyin 類)
$pinyin = Pinyin::get($title);
// 2. 非字母數字替換為連字符
$slug = preg_replace('/[^a-z0-9]+/i', '-', $pinyin);
// 3. 去首尾連字符、小寫
return trim(strtolower($slug), '-');
}
echo slugify('PHP 開發必知的 10 個技巧'); // php-kai-fa-bi-zhi-de-10-ge-ji-qiao
?>
isset($arr[$key]) 比 array_key_exists 快 2-3 倍(僅檢查鍵存在)。array_keys(array_flip($arr)) 比 array_unique 快(利用鍵唯一性)。in_array 查找:先 $flip = array_flip($bigArr),再用 isset($flip[$val]) O(1) 查找。內置函數是 C 級性能,善用它們比手寫循環更快、更穩。