Skip to content

8.7 实操:封装常用工具函数

本实操将封装一些常用的工具函数,这些函数可以在实际项目中反复使用。

功能需求

  1. 封装字符串处理函数
  2. 封装数组处理函数
  3. 封装时间处理函数
  4. 封装验证函数

实现代码

php
<?php
// 字符串处理函数
class StringUtil {
    // 生成随机字符串
    public static function randomString($length = 8) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
    
    // 截取字符串(支持中文)
    public static function truncate($string, $length, $suffix = '...') {
        if (mb_strlen($string, 'UTF-8') <= $length) {
            return $string;
        }
        return mb_substr($string, 0, $length, 'UTF-8') . $suffix;
    }
    
    // 清理HTML标签
    public static function cleanHtml($string) {
        return strip_tags($string);
    }
    
    // 转义HTML特殊字符
    public static function escapeHtml($string) {
        return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
    }
}

// 数组处理函数
class ArrayUtil {
    // 数组去重
    public static function unique($array) {
        return array_unique($array);
    }
    
    // 数组排序(支持关联数组)
    public static function sort($array, $key = null, $order = 'asc') {
        if ($key === null) {
            $order === 'asc' ? sort($array) : rsort($array);
            return $array;
        }
        
        usort($array, function($a, $b) use ($key, $order) {
            if ($order === 'asc') {
                return $a[$key] <=> $b[$key];
            } else {
                return $b[$key] <=> $a[$key];
            }
        });
        return $array;
    }
    
    // 数组分页
    public static function paginate($array, $page, $pageSize) {
        $total = count($array);
        $start = ($page - 1) * $pageSize;
        return array_slice($array, $start, $pageSize);
    }
    
    // 二维数组根据键值分组
    public static function groupBy($array, $key) {
        $result = [];
        foreach ($array as $item) {
            if (isset($item[$key])) {
                $result[$item[$key]][] = $item;
            }
        }
        return $result;
    }
}

// 时间处理函数
class TimeUtil {
    // 格式化时间
    public static function format($timestamp, $format = 'Y-m-d H:i:s') {
        return date($format, $timestamp);
    }
    
    // 获取相对时间
    public static function relativeTime($timestamp) {
        $now = time();
        $diff = $now - $timestamp;
        
        if ($diff < 60) {
            return '刚刚';
        } elseif ($diff < 3600) {
            return floor($diff / 60) . '分钟前';
        } elseif ($diff < 86400) {
            return floor($diff / 3600) . '小时前';
        } elseif ($diff < 2592000) {
            return floor($diff / 86400) . '天前';
        } else {
            return date('Y-m-d', $timestamp);
        }
    }
    
    // 计算两个时间差
    public static function diff($startTime, $endTime) {
        $diff = abs($endTime - $startTime);
        $days = floor($diff / 86400);
        $hours = floor(($diff % 86400) / 3600);
        $minutes = floor(($diff % 3600) / 60);
        $seconds = $diff % 60;
        
        return [
            'days' => $days,
            'hours' => $hours,
            'minutes' => $minutes,
            'seconds' => $seconds
        ];
    }
}

// 验证函数
class ValidateUtil {
    // 验证邮箱
    public static function isEmail($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }
    
    // 验证手机号(中国大陆)
    public static function isMobile($mobile) {
        return preg_match('/^1[3-9]\d{9}$/', $mobile);
    }
    
    // 验证身份证号(中国大陆)
    public static function isIdCard($idCard) {
        return preg_match('/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/', $idCard);
    }
    
    // 验证URL
    public static function isUrl($url) {
        return filter_var($url, FILTER_VALIDATE_URL) !== false;
    }
    
    // 验证密码强度
    public static function checkPasswordStrength($password) {
        $strength = 0;
        if (strlen($password) >= 8) $strength++;
        if (preg_match('/[A-Z]/', $password)) $strength++;
        if (preg_match('/[a-z]/', $password)) $strength++;
        if (preg_match('/[0-9]/', $password)) $strength++;
        if (preg_match('/[^A-Za-z0-9]/', $password)) $strength++;
        
        return $strength;
    }
}

// 测试示例
echo "<h3>字符串处理函数测试</h3>";
echo "随机字符串: " . StringUtil::randomString(10) . "<br>";
echo "截取字符串: " . StringUtil::truncate("这是一个很长的字符串,需要被截取", 10) . "<br>";
echo "清理HTML: " . StringUtil::cleanHtml("<p>Hello <b>World</b></p>") . "<br>";
echo "转义HTML: " . StringUtil::escapeHtml("<script>alert('xss')</script>") . "<br>";

echo "<h3>数组处理函数测试</h3>";
$testArray = [3, 1, 4, 1, 5, 9, 2, 6];
echo "去重前: " . implode(", ", $testArray) . "<br>";
echo "去重后: " . implode(", ", ArrayUtil::unique($testArray)) . "<br>";

$students = [
    ["name" => "张三", "score" => 95],
    ["name" => "李四", "score" => 88],
    ["name" => "王五", "score" => 92]
];
echo "<br>按分数排序: <br>";
$sortedStudents = ArrayUtil::sort($students, "score", "desc");
foreach ($sortedStudents as $student) {
    echo "姓名: " . $student["name"] . ", 分数: " . $student["score"] . "<br>";
}

echo "<h3>时间处理函数测试</h3>";
$timestamp = time() - 3600; // 1小时前
echo "格式化时间: " . TimeUtil::format($timestamp) . "<br>";
echo "相对时间: " . TimeUtil::relativeTime($timestamp) . "<br>";

$start = strtotime("2023-01-01");
$end = strtotime("2023-01-05");
$diff = TimeUtil::diff($start, $end);
echo "时间差: " . $diff["days"] . "天 " . $diff["hours"] . "小时 " . $diff["minutes"] . "分钟<br>";

echo "<h3>验证函数测试</h3>";
echo "邮箱验证: " . (ValidateUtil::isEmail("test@example.com") ? "有效" : "无效") . "<br>";
echo "手机号验证: " . (ValidateUtil::isMobile("13812345678") ? "有效" : "无效") . "<br>";
echo "身份证验证: " . (ValidateUtil::isIdCard("110101199001011234") ? "有效" : "无效") . "<br>";
echo "URL验证: " . (ValidateUtil::isUrl("https://www.example.com") ? "有效" : "无效") . "<br>";
echo "密码强度: " . ValidateUtil::checkPasswordStrength("Password123!") . "/5<br>";
?>

代码解析

  1. 字符串处理函数

    • randomString():生成指定长度的随机字符串
    • truncate():截取字符串,支持中文
    • cleanHtml():清理HTML标签
    • escapeHtml():转义HTML特殊字符
  2. 数组处理函数

    • unique():数组去重
    • sort():数组排序,支持关联数组
    • paginate():数组分页
    • groupBy():二维数组根据键值分组
  3. 时间处理函数

    • format():格式化时间
    • relativeTime():获取相对时间(如"5分钟前")
    • diff():计算两个时间差
  4. 验证函数

    • isEmail():验证邮箱格式
    • isMobile():验证手机号格式
    • isIdCard():验证身份证号格式
    • isUrl():验证URL格式
    • checkPasswordStrength():检查密码强度

运行结果

执行上述代码后,会在浏览器中显示各种工具函数的测试结果。

扩展练习

  1. 扩展字符串处理函数,添加更多功能
  2. 扩展数组处理函数,添加数组合并、差集等功能
  3. 扩展时间处理函数,添加更多时间格式化选项
  4. 扩展验证函数,添加更多验证规则

© 2026 编程马·菜鸟教程 版权所有