Skip to content

标准库

概述

PHP拥有丰富的标准库,提供了大量内置函数和扩展来处理各种常见任务。本章将介绍最重要的标准库功能,包括字符串处理、数组操作、日期时间、数学函数、文件系统操作等。

字符串函数

基本字符串操作

php
<?php
$text = "  Hello World  ";

// 字符串长度和基本操作
echo "长度: " . strlen($text) . "\n";
echo "UTF-8长度: " . mb_strlen("你好世界") . "\n";
echo "大写: " . strtoupper($text) . "\n";
echo "小写: " . strtolower($text) . "\n";
echo "去除空白: '" . trim($text) . "'\n";

// 字符串查找和替换
$haystack = "The quick brown fox";
echo "查找位置: " . strpos($haystack, "quick") . "\n";
echo "替换: " . str_replace("fox", "cat", $haystack) . "\n";

// 字符串分割和连接
$fruits = explode(",", "apple,banana,orange");
$joined = implode(" | ", $fruits);
echo "连接: $joined\n";

// 格式化字符串
$name = "张三";
$age = 25;
$formatted = sprintf("姓名: %s, 年龄: %d", $name, $age);
echo "格式化: $formatted\n";
?>

数组函数

数组操作

php
<?php
// 数组创建和基本操作
$numbers = [1, 2, 3, 4, 5];
$fruits = ["apple", "banana", "orange"];

echo "数组长度: " . count($numbers) . "\n";

// 添加和移除元素
array_push($fruits, "grape");
$last = array_pop($fruits);
echo "移除的元素: $last\n";

// 数组合并和切片
$merged = array_merge($numbers, [6, 7, 8]);
$slice = array_slice($numbers, 1, 3);
print_r($slice);

// 数组搜索和过滤
$students = [
    ['name' => '张三', 'score' => 85],
    ['name' => '李四', 'score' => 92],
    ['name' => '王五', 'score' => 78]
];

// 获取特定列
$scores = array_column($students, 'score');
print_r($scores);

// 过滤数组
$excellent = array_filter($students, function($student) {
    return $student['score'] >= 90;
});
print_r($excellent);

// 数组排序
sort($numbers);
usort($students, function($a, $b) {
    return $b['score'] - $a['score'];
});
print_r($students);
?>

日期和时间函数

基本日期时间操作

php
<?php
// 当前时间
echo "当前时间戳: " . time() . "\n";
echo "当前日期: " . date('Y-m-d H:i:s') . "\n";

// 格式化日期
$timestamp = time();
echo "年份: " . date('Y', $timestamp) . "\n";
echo "中文格式: " . date('Y年m月d日 H:i:s') . "\n";

// 相对时间
echo "明天: " . date('Y-m-d', strtotime('+1 day')) . "\n";
echo "下周: " . date('Y-m-d', strtotime('+1 week')) . "\n";

// DateTime类
$date1 = new DateTime();
$date2 = new DateTime('2024-01-15 10:30:00');

echo "当前时间: " . $date1->format('Y-m-d H:i:s') . "\n";
echo "指定时间: " . $date2->format('Y-m-d H:i:s') . "\n";

// 日期计算
$date = new DateTime('2024-01-01');
$date->add(new DateInterval('P1M')); // 加1个月
echo "加时间后: " . $date->format('Y-m-d') . "\n";

// 时区处理
$utc = new DateTime('2024-01-15 12:00:00', new DateTimeZone('UTC'));
$shanghai = $utc->setTimezone(new DateTimeZone('Asia/Shanghai'));
echo "上海时间: " . $shanghai->format('Y-m-d H:i:s T') . "\n";
?>

数学函数

基本数学运算

php
<?php
// 基本函数
echo "绝对值: " . abs(-5) . "\n";
echo "最大值: " . max([1, 3, 2, 5, 4]) . "\n";
echo "向上取整: " . ceil(3.14) . "\n";
echo "四舍五入: " . round(3.14159, 2) . "\n";

// 幂运算和开方
echo "幂运算: " . pow(2, 3) . "\n";
echo "平方根: " . sqrt(16) . "\n";

// 随机数
echo "随机整数: " . mt_rand(1, 100) . "\n";
echo "随机小数: " . mt_rand() / mt_getrandmax() . "\n";

// 进制转换
echo "十进制转二进制: " . decbin(255) . "\n";
echo "十进制转十六进制: " . dechex(255) . "\n";

// 统计函数
$scores = [85, 92, 78, 95, 88];
$sum = array_sum($scores);
$average = $sum / count($scores);
echo "总和: $sum, 平均值: $average\n";
?>

文件系统函数

文件和目录操作

php
<?php
$filename = 'test.txt';
$directory = '.';

// 文件检查
echo "文件存在: " . (file_exists($filename) ? "是" : "否") . "\n";
echo "是否为文件: " . (is_file($filename) ? "是" : "否") . "\n";
echo "是否为目录: " . (is_dir($directory) ? "是" : "否") . "\n";

// 文件信息
if (file_exists($filename)) {
    echo "文件大小: " . filesize($filename) . " 字节\n";
    echo "修改时间: " . date('Y-m-d H:i:s', filemtime($filename)) . "\n";
}

// 路径信息
$path = '/path/to/document.pdf';
echo "目录名: " . dirname($path) . "\n";
echo "文件名: " . basename($path) . "\n";
echo "扩展名: " . pathinfo($path, PATHINFO_EXTENSION) . "\n";

// 目录遍历
$files = scandir('.');
echo "当前目录文件:\n";
foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        echo "- $file\n";
    }
}

// 使用glob查找文件
$phpFiles = glob('*.php');
echo "PHP文件数量: " . count($phpFiles) . "\n";
?>

JSON和序列化

JSON处理

php
<?php
// 数组转JSON
$data = [
    'name' => '张三',
    'age' => 25,
    'hobbies' => ['读书', '游泳', '编程']
];

$json = json_encode($data, JSON_UNESCAPED_UNICODE);
echo "JSON: $json\n";

// JSON转数组
$decoded = json_decode($json, true);
print_r($decoded);

// 错误处理
$invalidJson = '{"name": "张三", "age":}';
$result = json_decode($invalidJson);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON错误: " . json_last_error_msg() . "\n";
}

// 序列化
$serialized = serialize($data);
echo "序列化: $serialized\n";

$unserialized = unserialize($serialized);
print_r($unserialized);
?>

过滤器函数

数据验证和过滤

php
<?php
// 验证过滤器
$email = 'user@example.com';
$url = 'https://www.example.com';
$int = '123';

echo "邮箱验证: " . (filter_var($email, FILTER_VALIDATE_EMAIL) ? '有效' : '无效') . "\n";
echo "URL验证: " . (filter_var($url, FILTER_VALIDATE_URL) ? '有效' : '无效') . "\n";
echo "整数验证: " . (filter_var($int, FILTER_VALIDATE_INT) !== false ? '有效' : '无效') . "\n";

// 清理过滤器
$string = '<script>alert("xss")</script>Hello!';
echo "清理字符串: " . filter_var($string, FILTER_SANITIZE_STRING) . "\n";
echo "清理邮箱: " . filter_var('user@exa mple.com', FILTER_SANITIZE_EMAIL) . "\n";

// 批量过滤
$data = [
    'email' => 'user@example.com',
    'age' => '25',
    'name' => '<script>alert("xss")</script>张三'
];

$filters = [
    'email' => FILTER_VALIDATE_EMAIL,
    'age' => FILTER_VALIDATE_INT,
    'name' => FILTER_SANITIZE_STRING
];

$result = filter_var_array($data, $filters);
print_r($result);
?>

实用工具函数

常用工具

php
<?php
// 生成唯一ID和哈希
echo "UUID: " . uniqid() . "\n";
echo "MD5: " . md5('password') . "\n";
echo "SHA256: " . hash('sha256', 'password') . "\n";

// 密码哈希(安全)
$password = 'mypassword';
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
echo "安全哈希: $hashedPassword\n";

if (password_verify($password, $hashedPassword)) {
    echo "密码验证成功\n";
}

// 编码和解码
$data = "Hello World";
echo "Base64编码: " . base64_encode($data) . "\n";
echo "URL编码: " . urlencode($data) . "\n";

// 内存和性能
$startTime = microtime(true);
$startMemory = memory_get_usage();

// 执行操作
$sum = array_sum(range(1, 10000));

$endTime = microtime(true);
$endMemory = memory_get_usage();

echo "执行时间: " . ($endTime - $startTime) . " 秒\n";
echo "内存使用: " . ($endMemory - $startMemory) . " 字节\n";

// 系统信息
echo "PHP版本: " . phpversion() . "\n";
echo "操作系统: " . php_uname('s') . "\n";
?>

实用类示例

工具类

php
<?php
class Utils {
    // 格式化字节数
    public static function formatBytes($bytes, $precision = 2) {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        
        for ($i = 0; $bytes >= 1024 && $i < count($units) - 1; $i++) {
            $bytes /= 1024;
        }
        
        return round($bytes, $precision) . ' ' . $units[$i];
    }
    
    // 生成随机字符串
    public static function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        
        return $randomString;
    }
    
    // 验证邮箱
    public static function isValidEmail($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }
    
    // 清理HTML
    public static function cleanHtml($html) {
        return htmlspecialchars(strip_tags($html), ENT_QUOTES, 'UTF-8');
    }
    
    // 截取文本(支持中文)
    public static function truncate($text, $length, $suffix = '...') {
        if (mb_strlen($text, 'UTF-8') <= $length) {
            return $text;
        }
        
        return mb_substr($text, 0, $length, 'UTF-8') . $suffix;
    }
}

// 使用示例
echo "格式化字节: " . Utils::formatBytes(1048576) . "\n";
echo "随机字符串: " . Utils::generateRandomString(12) . "\n";
echo "邮箱验证: " . (Utils::isValidEmail('test@example.com') ? '有效' : '无效') . "\n";
echo "截取文本: " . Utils::truncate('这是一段很长的中文文本内容', 10) . "\n";
?>

错误处理和调试

调试函数

php
<?php
// 调试输出
$data = [
    'user' => 'admin',
    'permissions' => ['read', 'write', 'delete']
];

echo "var_dump输出:\n";
var_dump($data);

echo "\nprint_r输出:\n";
print_r($data);

// 自定义错误处理
function customErrorHandler($severity, $message, $file, $line) {
    echo "错误: [$severity] $message$file$line\n";
}

set_error_handler('customErrorHandler');

// 性能监控
class PerformanceMonitor {
    private $startTime;
    
    public function start() {
        $this->startTime = microtime(true);
    }
    
    public function end($operation = '') {
        $endTime = microtime(true);
        $duration = $endTime - $this->startTime;
        echo "$operation 耗时: " . number_format($duration, 4) . " 秒\n";
        echo "内存使用: " . number_format(memory_get_usage() / 1024 / 1024, 2) . " MB\n";
    }
}

$monitor = new PerformanceMonitor();
$monitor->start();

// 执行一些操作
$sum = array_sum(range(1, 100000));

$monitor->end('数组求和');
?>

最佳实践

使用建议

  1. 优先使用内置函数:PHP内置函数通常更快更安全
  2. 注意字符编码:处理中文时使用mb_*函数
  3. 验证用户输入:使用filter_var等函数验证数据
  4. 错误处理:始终检查函数返回值和可能的错误
  5. 性能考虑:在循环中避免重复的函数调用

安全性考虑

  • 验证和过滤所有用户输入
  • 使用适当的数据清理函数
  • 避免信息泄露(如文件路径、错误信息)
  • 使用安全的密码哈希方法

总结

PHP标准库提供了丰富的功能:

  • 字符串函数:文本处理和格式化
  • 数组函数:数据操作和算法处理
  • 日期时间:时间处理和计算
  • 数学函数:数值计算和统计
  • 文件系统:文件和目录操作
  • 数据处理:JSON、序列化、过滤
  • 工具函数:编码、哈希、调试

熟练掌握这些标准库函数能够大大提高开发效率和代码质量。在下一章中,我们将了解PHP的学习资源和进阶方向。

本站内容仅供学习和研究使用。