跳到主要内容

PHP 常用标准库

本章将介绍 PHP 常用的内置函数和扩展。

数组函数

<?php
$arr = [1, 2, 3, 4, 5];

// 基本操作
count($arr); // 5 - 元素数量
in_array(3, $arr); // true - 检查值是否存在
array_search(3, $arr); // 2 - 查找键
array_key_exists(0, $arr); // true - 检查键

// 添加/删除
array_push($arr, 6, 7); // 末尾添加
array_pop($arr); // 删除末尾元素
array_unshift($arr, 0); // 开头添加
array_shift($arr); // 删除开头元素

// 切片/合并
array_slice($arr, 1, 3); // [2, 3, 4] - 切片
array_merge([1, 2], [3, 4]); // [1, 2, 3, 4] - 合并
array_combine(['a', 'b'], [1, 2]); // ['a' => 1, 'b' => 2]

// 过滤/映射
array_filter($arr, fn($v) => $v > 2); // [3, 4, 5]
array_map(fn($v) => $v * 2, $arr); // [2, 4, 6, 8, 10]
array_reduce($arr, fn($c, $v) => $c + $v, 0); // 15

// 排序
sort($arr); // 升序(重新索引)
rsort($arr); // 降序
asort($arr); // 按值升序(保持键)
ksort($arr); // 按键升序
usort($arr, fn($a, $b) => $a <=> $b); // 自定义排序

// 其他
array_unique([1, 1, 2, 2, 3]); // [1, 2, 3] - 去重
array_reverse($arr); // 反转
array_flip(['a' => 1]); // [1 => 'a'] - 键值互换
array_values(['a' => 1]); // [1] - 获取所有值
array_keys(['a' => 1]); // ['a'] - 获取所有键
?>

字符串函数

<?php
$str = "Hello World";

// 长度和查找
strlen($str); // 11 - 字节长度
mb_strlen("你好"); // 2 - 字符长度
strpos($str, "World"); // 6 - 查找位置
stripos($str, "world"); // 6 - 不区分大小写
substr_count($str, "l"); // 3 - 统计出现次数

// 截取和替换
substr($str, 0, 5); // "Hello" - 截取
mb_substr("你好世界", 0, 2); // "你好"
str_replace("World", "PHP", $str); // "Hello PHP"
substr_replace($str, "PHP", 6); // "Hello PHP"

// 大小写
strtolower($str); // "hello world"
strtoupper($str); // "HELLO WORLD"
ucfirst("hello"); // "Hello"
ucwords("hello world"); // "Hello World"

// 去除空白
trim(" hello "); // "hello"
ltrim(" hello "); // "hello "
rtrim(" hello "); // " hello"

// 分割和连接
explode(",", "a,b,c"); // ["a", "b", "c"]
implode(",", ["a", "b", "c"]); // "a,b,c"
str_split("abc"); // ["a", "b", "c"]

// 格式化
sprintf("%s %d", "Age:", 25); // "Age: 25"
printf("%s %d\n", "Age:", 25); // 输出并换行
number_format(1234567.89, 2); // "1,234,567.89"

// HTML
htmlspecialchars("<script>"); // "&lt;script&gt;"
strip_tags("<p>Hello</p>"); // "Hello"
nl2br("Hello\nWorld"); // "Hello<br />\nWorld"
?>

日期时间函数

<?php
// 当前时间
echo time(); // Unix 时间戳
echo date("Y-m-d H:i:s"); // 格式化日期
echo microtime(true); // 微秒时间戳

// 创建时间
$date = date_create("2024-01-15");
$date = new DateTime("2024-01-15");

// 格式化
echo $date->format("Y-m-d"); // "2024-01-15"
echo date("Y-m-d", strtotime("+1 day")); // 明天

// 修改日期
$date->modify("+1 day");
$date->modify("+1 month");
$date->modify("+1 year");

// 日期比较
$date1 = new DateTime("2024-01-01");
$date2 = new DateTime("2024-01-15");
$diff = $date1->diff($date2);
echo $diff->days; // 14

// 日期间隔
$interval = new DateInterval("P1D"); // 1 天
$interval = new DateInterval("P1M"); // 1 月
$interval = new DateInterval("PT1H"); // 1 小时

// 时区
$tz = new DateTimeZone("Asia/Shanghai");
$date = new DateTime("now", $tz);

// 常用格式字符
// Y - 4位年份
// m - 2位月份
// d - 2位日期
// H - 24小时制小时
// i - 分钟
// s - 秒
// w - 星期几(0-6)
// W - 年中第几周
?>

文件系统函数

<?php
// 文件操作
file_exists("test.txt"); // 检查存在
is_file("test.txt"); // 是否是文件
is_dir("folder"); // 是否是目录
is_readable("test.txt"); // 是否可读
is_writable("test.txt"); // 是否可写

// 读取
file_get_contents("test.txt"); // 读取整个文件
file("test.txt"); // 读取到数组
fread($handle, 1024); // 读取指定长度
fgets($handle); // 读取一行

// 写入
file_put_contents("test.txt", "content");
fwrite($handle, "content");

// 文件信息
filesize("test.txt"); // 文件大小
filemtime("test.txt"); // 修改时间
fileatime("test.txt"); // 访问时间
filetype("test.txt"); // 文件类型

// 目录操作
mkdir("folder"); // 创建目录
rmdir("folder"); // 删除空目录
scandir("folder"); // 列出目录内容
opendir("folder"); // 打开目录
readdir($handle); // 读取目录

// 路径操作
basename("/path/to/file.txt"); // "file.txt"
dirname("/path/to/file.txt"); // "/path/to"
pathinfo("/path/to/file.txt"); // 路径信息数组
realpath("test.txt"); // 绝对路径
?>

JSON 函数

<?php
$data = ["name" => "张三", "age" => 25];

// 编码
$json = json_encode($data);
// {"name":"\u5f20\u4e09","age":25}

// 编码选项
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
// {"name":"张三","age":25}

$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
// 格式化输出

// 解码
$obj = json_decode($json); // 对象
$arr = json_decode($json, true); // 关联数组

// 错误处理
$result = json_decode($invalid);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_last_error_msg();
}

// PHP 7.3+ 异常模式
try {
$data = json_decode($json, false, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo $e->getMessage();
}
?>

cURL 函数

<?php
// 初始化
$ch = curl_init("https://api.example.com/users");

// 设置选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'name' => '张三',
'age' => 25
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Bearer token'
]);

// 执行
$response = curl_exec($ch);

// 获取信息
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// 关闭
curl_close($ch);

// 封装函数
function httpRequest($url, $method = 'GET', $data = null, $headers = []) {
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}

if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}

$response = curl_exec($ch);
$error = curl_error($ch);

curl_close($ch);

if ($error) {
throw new Exception($error);
}

return $response;
}
?>

正则表达式

<?php
$str = "Hello World 123";

// 匹配
preg_match("/\d+/", $str, $matches); // ["123"]
preg_match_all("/\d/", $str, $matches); // ["1", "2", "3"]

// 替换
preg_replace("/\d+/", "NUM", $str); // "Hello World NUM"

// 分割
preg_split("/\s+/", "a b c"); // ["a", "b", "c"]

// 过滤
$arr = ["abc", "123", "def"];
preg_grep("/^[a-z]+$/", $arr); // ["abc", "def"]

// 常用模式
$patterns = [
'email' => '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/',
'phone' => '/^1[3-9]\d{9}$/',
'url' => '/^https?:\/\/[^\s]+$/',
'date' => '/^\d{4}-\d{2}-\d{2}$/',
'ip' => '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/'
];
?>

其他常用函数

<?php
// 数学
abs(-5); // 5
round(3.5); // 4
ceil(3.1); // 4
floor(3.9); // 3
max(1, 2, 3); // 3
min(1, 2, 3); // 1
rand(1, 100); // 随机数
mt_rand(1, 100); // 更好的随机数
sqrt(16); // 4
pow(2, 3); // 8

// 随机字节
bin2hex(random_bytes(16)); // 32位随机字符串

// 编码
base64_encode("hello"); // "aGVsbG8="
base64_decode("aGVsbG8="); // "hello"

// URL
urlencode("你好"); // "%E4%BD%A0%E5%A5%BD"
urldecode("%E4%BD%A0%E5%A5%BD"); // "你好"

// 序列化
$serialized = serialize(["a" => 1]);
$arr = unserialize($serialized);

// 变量类型
is_int(1); // true
is_float(1.5); // true
is_string("a"); // true
is_array([]); // true
is_object(new stdClass()); // true
is_null(null); // true
empty(""); // true
isset($var); // 检查是否设置

// 类型转换
intval("123"); // 123
floatval("1.5"); // 1.5
strval(123); // "123"
boolval(1); // true

// 调试
var_dump($var); // 打印变量信息
print_r($arr); // 打印数组
debug_zval_dump($var); // 调试用

// 执行时间
$start = microtime(true);
// ... 代码 ...
$time = microtime(true) - $start;
echo "执行时间:{$time}秒";
?>

小结

本章我们学习了 PHP 常用的标准库函数:

  1. 数组函数:排序、过滤、映射、合并
  2. 字符串函数:查找、替换、分割、格式化
  3. 日期时间函数:格式化、计算、时区
  4. 文件系统函数:读写、目录操作
  5. JSON 函数:编码解码
  6. cURL 函数:HTTP 请求
  7. 正则表达式:匹配、替换、分割
  8. 其他常用函数:数学、编码、调试