PHP 内置函数详解

PHP 内置函数字典:按类别组织高频函数,每条签名+示例。全部函数官方文档见 php.net,本篇覆盖日常 90%。

1. 字符串 – 判断与查找

描述

str_contains 系(8.0+)取代 strpos 判断;大小写不敏感变体加 i。

语法和示例

str_contains('hello', 'ell');      // true
str_starts_with('hello', 'he');    // true
str_ends_with('hello', 'lo');      // true
stristr('Hello', 'L');             // 大小写不敏感的首次出现
strpos('hello', 'l');              // 2(未找到 false——必须 !== false 判断)

2. 字符串 – 截取与替换

描述

substr 定长截取;str_replace 批量替换(数组参数);负偏移从尾数。

语法和示例

substr('hello', 1, 3);            // 'ell'
substr('hello', -2);               // 'lo'
str_replace('a', 'b', 'banana');   // 'bbnbnb'
str_replace(['a','b'], 'x', $s);    // 多对一
str_replace(['a','b'], ['x','y'], $s); // 成对替换
substr_replace($s, 'XX', 0, 2);

3. 字符串 – 大小写与修剪

描述

trim 可传字符集;mb_ 系处理 Unicode 大小写。

语法和示例

trim('  x  ');  ltrim($s);  rtrim($s);
trim('/a/b/', '/');                 // 'a/b'
strtoupper('hi'); strtolower('HI');
ucfirst('hi'); ucwords('hi there');
mb_strtolower('HÉLLO');             // Unicode 正确

4. 字符串 – 分割与拼接

描述

explode 指定次数;implode 数组转串;wordwrap 自动换行。

语法和示例

explode(',', 'a,b,c');             // ['a','b','c']
explode(',', 'a,b,c', 2);          // ['a','b,c'] 最多 2 段
implode('-', ['a','b']);           // 'a-b'
str_pad('7', 3, '0', STR_PAD_LEFT); // '007'
number_format(1234567.89, 2);      // '1,234,567.89'
nl2br("a\nb");

5. 字符串 – 编码与安全

描述

htmlspecialchars 防 XSS 必用;urlencode 用于查询串。

语法和示例

htmlspecialchars('<b>&</b>', ENT_QUOTES, 'UTF-8');
html_entity_decode('&');
urlencode('中文 a');                // 查询串
rawurlencode('a b');               // 路径段
base64_encode($data);  base64_decode($b64, true);

6. 数组 – 增删改

描述

array_push/pop/shift/unshift 四栈队列操作;unset 删键。

语法和示例

$q = [];
$q[] = 'a';                    // push
array_push($q, 'b', 'c');
array_pop($q);                 // 'c'
array_shift($q);               // 'a'
array_unshift($q, 'head');
unset($arr['key']);             // 删键(不留空洞)
array_splice($arr, 1, 2);       // 原地删除并返回段

7. 数组 – 检索与判断

描述

in_array 严格模式加 true;array_search 返回键。

语法和示例

in_array('php', $arr);              // 松散
in_array('1', ['1'], true);         // false:严格
in_array(1, ['1', 1], true);        // true
array_search('b', ['a','b']);       // 1(键),未找到 false
array_key_exists('k', $map);
isset($map['k']);                   // 存在且非 null
array_values($map);  array_keys($map);

8. 数组 – 排序

描述

带 a 保键、带 k 按键、带 u 自定义。

语法和示例

sort($arr);           // 值升序重排键
rsort($arr);          // 值降序
asort($map);          // 值升序保键
arsort($map); ksort($map); krsort($map);
usort($items, fn($a,$b) => $a['age'] <=> $b['age']);
usort($items, fn($a,$b) => $b['score'] <=> $a['score']);

9. 数组 – 集合运算

描述

+ 并集保左;merge 数字键重排;intersect/diff。

语法和示例

$a + $b;                          // 左优先补缺
array_merge($a, $b);               // 字符串键后者覆盖,数字键重排
array_merge_recursive($a, $b);     // 递归合并
array_intersect($a, $b);           // 值交集
array_diff($a, $b);                // 在 a 不在 b
array_intersect_key($a, $b);  array_diff_key($a, $b);

10. 数组 – 映射过滤归约

描述

array_map 多数组并行;array_filter 保键(要重排用 values 包一层)。

语法和示例

array_map(fn($x) => $x * 2, [1,2]);         // [2,4]
array_map(fn($a,$b) => $a+$b, [1,2],[10,20]); // [11,22]
array_filter($arr, fn($x) => $x > 0);       // 保键
array_values(array_filter($arr, 'is_string')); // 重排键
array_reduce($arr, fn($c,$x) => $c+$x, 0);
array_sum($arr);  array_product($arr);
array_walk($arr, function (&$v, $k) { $v *= 2; });  // 引用改写

11. 数组 – 切片重组

描述

slice 保留键需第四参;chunk 分批;column 抽列。

语法和示例

array_slice($arr, 1, 2);              // 偏移 1 取 2(默认重排数字键)
array_slice($arr, 1, 2, true);        // 保键
array_chunk($arr, 100);               // 分批处理大数据
array_column($rows, 'name');          // 抽列
array_column($rows, 'name', 'id');    // id 为键的映射
array_combine($keys, $vals);
array_flip($map);                     // 键值互换
array_unique($arr);  array_reverse($arr);
range(1, 10);  range('a', 'e');

12. 数学函数

描述

intdiv 整除;bc 系任意精度;round 银行家舍入。

语法和示例

abs(-3);  max(1,5,3);  min([2,8]);
intdiv(7, 2);      // 3
7 % 2;             // 1(符号跟被除数:-7%2 == -1)
round(2.5);        // 3(PHP 是四舍五入,0.5 进位)
ceil(1.2);  floor(1.8);
pow(2, 10);  sqrt(16);  fmod(7, 2);
mt_rand(1, 100);   random_int(1, 100);   // 密码学安全
number_format / floatval / intval / is_numeric
bcadd('0.1','0.2',2);  // '0.30'——算钱

13. 日期时间函数

描述

date 格式化;strtotime 人类语感解析;DateTimeImmutable 面向对象。

语法和示例

date('Y-m-d H:i:s');  date('Y年m月d日', $ts);
strtotime('+1 day');  strtotime('next Monday');
strtotime('2026-10-29 15:00');
time();   microtime(true);    // 时间戳 / 微秒浮点
mktime(15, 0, 0, 10, 29, 2026);
date_default_timezone_set('Asia/Shanghai');
$dt = new DateTimeImmutable('+30 days');
$dt->format('Y-m-d');  $dt->getTimestamp();
$a->diff($b)->days;

14. 文件系统函数

描述

file_get_contents 整读(支持 URL);fopen 系流式;is_file 系判断。

语法和示例

file_get_contents('a.txt');
file_get_contents('https://api.x.com', false, $ctx);
file_put_contents('a.txt', $data, FILE_APPEND | LOCK_EX);
file('a.txt');                      // 按行入数组
fopen / fgets / fwrite / fclose;
is_file / is_dir / file_exists;
filesize / filemtime / touch;
mkdir('/tmp/x/y', 0755, true);       // 递归建
scandir('/etc');  glob('/tmp/*.log');
copy / rename / unlink / rmdir;
tempnam(sys_get_temp_dir(), 'pre');

15. JSON 函数

描述

encode 三常量组合;decode assoc;深度与异常。

语法和示例

json_encode($data,
    JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
json_decode($json, true, 512, JSON_THROW_ON_ERROR);
json_last_error();  json_last_error_msg();   // 不用 THROW 时的手动检查
json_validate($str);                          // 8.3+ 只验不转

16. 正则函数

描述

preg 系四件套;预编译场景直接字面量。

语法和示例

preg_match('/(\d{4})-(\d{2})/', $s, $m);   // $m[1] $m[2]
preg_match_all('/#(\w+)/', $s, $all);        // $all[1]
preg_replace('/\s+/', ' ', $s);
preg_replace_callback('/\w+/', fn($m) => strtoupper($m[0]), $s);
preg_split('/[,;\s]+/', $s);
preg_grep('/^a/', $arr);                      // 过滤数组

17. 变量与类型函数

描述

is_* 家族;empty/isset 语义;gettype/debug。

语法和示例

gettype($v); get_debug_type($v);     // 8.0+ 更精确(如 'int' 非 'integer')
is_int / is_float / is_string / is_bool / is_array / is_object / is_null;
is_numeric('1.5');   // true;'0x1A' 是 false
is_callable($fn);  function_exists('strlen');
empty($v);    // ''/0/'0'/[]/null/false → true;未定义也不报错
isset($v);    // 已定义且非 null
var_dump($x); print_r($x, true);  serialize / unserialize;
compact('a','b');  extract($assoc);

18. 输出与头

描述

header 必须在任何输出前;ob 系控制缓冲。

语法和示例

header('Content-Type: application/json; charset=utf-8');
header('Location: /login', true, 302);
http_response_code(404);
setcookie('k', 'v', ['expires' => time()+3600, 'httponly' => true, 'samesite' => 'Lax']);
ob_start();  $buf = ob_get_clean();
phpinfo();  ini_get('memory_limit');  ini_set('max_execution_time', '120');

19. 错误与日志

描述

error_log 落日志;trigger_error 用户级;set_error_handler 统一。

语法和示例

error_log((string) $e);              // strict 下对象要显式转字符串
error_log($msg, 3, '/tmp/app.log');  // 追加到文件
trigger_error('自定义警告', E_USER_WARNING);
set_error_handler(function ($no, $msg, $file, $line) {
    throw new ErrorException($msg, 0, $no, $file, $line);
});
error_reporting(E_ALL);
set_exception_handler(function (Throwable $e) { /* 兜底 */ });

20. 加密与哈希

描述

password_* 四件套是存密码唯一正确方式;hash_equals 防时序。

语法和示例

password_hash('明文', PASSWORD_DEFAULT);      // 自适应 bcrypt
password_verify('明文', $hash);                // 验证
password_needs_rehash($hash, PASSWORD_DEFAULT);
hash('sha256', $data);
hash_hmac('sha256', $data, $key);
hash_equals($known, $user);      // 常量时间比较
random_bytes(16);  random_int(1, 100);
md5 / sha1 仅校验用途,不再适合安全场景

21. 网络请求(服务端)

描述

file_get_contents 带 stream context 发 POST;curl 完整控制。

语法和示例

$ctx = stream_context_create(['http' => [
    'method'  => 'POST',
    'header'  => "Content-Type: application/json\r\n",
    'content' => json_encode($data),
    'timeout' => 10,
]]);
file_get_contents('https://api.x.com', false, $ctx);
// 复杂需求:curl(见字典「常用扩展」条目)
暂无评论

发送评论 编辑评论

|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇