PHP 字符串工具类函数

wen PHP项目 5
<?php
class StringHelper
{
    /**
     * 检查字符串是否以指定子串开头
     *
     * @param string $haystack 完整字符串
     * @param string $needle 需要检查的前缀
     * @return bool
     */
    public static function startsWith($haystack, $needle)
    {
        return strncmp($haystack, $needle, strlen($needle)) === 0;
    }
    /**
     * 检查字符串是否以指定子串结尾
     *
     * @param string $haystack 完整字符串
     * @param string $needle 需要检查的后缀
     * @return bool
     */
    public static function endsWith($haystack, $needle)
    {
        return $needle === '' || substr($haystack, -strlen($needle)) === $needle;
    }
    /**
     * 截取字符串(支持中文字符)
     *
     * @param string $str 原始字符串
     * @param int $start 开始位置
     * @param int|null $length 截取长度
     * @param string $encoding 字符编码
     * @return string
     */
    public static function substr($str, $start, $length = null, $encoding = 'UTF-8')
    {
        if ($length === null) {
            return mb_substr($str, $start, mb_strlen($str, $encoding), $encoding);
        }
        return mb_substr($str, $start, $length, $encoding);
    }
    /**
     * 截取指定长度的字符串,超出部分用省略号代替
     *
     * @param string $str 原始字符串
     * @param int $length 最大长度
     * @param string $suffix 追加的省略号
     * @return string
     */
    public static function truncate($str, $length, $suffix = '...')
    {
        if (mb_strlen($str) <= $length) {
            return $str;
        }
        return mb_substr($str, 0, $length - mb_strlen($suffix)) . $suffix;
    }
    /**
     * 生成随机字符串
     *
     * @param int $length 字符串长度
     * @param string $type 类型:alnum(字母数字), alpha(字母), numeric(数字), hex(十六进制)
     * @return string
     */
    public static function random($length = 16, $type = 'alnum')
    {
        switch ($type) {
            case 'alpha':
                $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                break;
            case 'numeric':
                $characters = '0123456789';
                break;
            case 'hex':
                $characters = '0123456789abcdef';
                break;
            default:
                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        }
        $randomString = '';
        $max = strlen($characters) - 1;
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[random_int(0, $max)];
        }
        return $randomString;
    }
    /**
     * 驼峰命名转下划线命名
     *
     * @param string $str 驼峰命名字符串
     * @return string
     */
    public static function camelToSnake($str)
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $str));
    }
    /**
     * 下划线命名转驼峰命名
     *
     * @param string $str 下划线命名字符串
     * @param bool $ucfirst 首字母是否大写
     * @return string
     */
    public static function snakeToCamel($str, $ucfirst = false)
    {
        $str = str_replace('_', '', ucwords($str, '_'));
        if (!$ucfirst) {
            $str = lcfirst($str);
        }
        return $str;
    }
    /**
     * 判断字符串是否包含中文字符
     *
     * @param string $str 要检查的字符串
     * @return bool
     */
    public static function hasChinese($str)
    {
        return preg_match('/[\x{4e00}-\x{9fa5}]/u', $str) > 0;
    }
    /**
     * 移除字符串中的空白字符(包括空格、制表符、换行等)
     *
     * @param string $str 原始字符串
     * @return string
     */
    public static function removeWhiteSpace($str)
    {
        return preg_replace('/\s+/', '', $str);
    }
    /**
     * 获取字符串的MD5值
     *
     * @param string $str 原始字符串
     * @return string
     */
    public static function md5($str)
    {
        return md5($str);
    }
    /**
     * 检查字符串是否为有效的URL
     *
     * @param string $url 要检查的URL
     * @return bool
     */
    public static function isValidUrl($url)
    {
        return filter_var($url, FILTER_VALIDATE_URL) !== false;
    }
    /**
     * 检查字符串是否为有效的邮箱地址
     *
     * @param string $email 要检查的邮箱
     * @return bool
     */
    public static function isValidEmail($email)
    {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }
    /**
     * 隐藏部分手机号码
     *
     * @param string $phone 手机号码
     * @param int $start 开始隐藏位置
     * @param int $length 隐藏长度
     * @param string $replace 替换字符
     * @return string
     */
    public static function maskPhone($phone, $start = 3, $length = 4, $replace = '*')
    {
        $result = $phone;
        if (strlen($phone) >= ($start + $length)) {
            $mask = str_repeat($replace, $length);
            $result = substr_replace($phone, $mask, $start, $length);
        }
        return $result;
    }
    /**
     * 数字金额转大写金额(支持到亿元)
     *
     * @param float $amount 金额数字
     * @return string
     */
    public static function amountToChinese($amount)
    {
        $units = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿'];
        $nums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
        $amount = number_format($amount, 2, '.', '');
        $parts = explode('.', $amount);
        $integerPart = $parts[0];
        $decimalPart = isset($parts[1]) ? $parts[1] : '';
        $integerLength = strlen($integerPart);
        $result = '';
        for ($i = 0; $i < $integerLength; $i++) {
            $digit = (int)$integerPart[$i];
            $result .= $nums[$digit];
            if ($digit != 0 || ($i > 0 && $integerPart[$i-1] != '0')) {
                $result .= $units[$integerLength - 1 - $i];
            }
        }
        if ($decimalPart) {
            $result .= '点';
            for ($i = 0; $i < strlen($decimalPart); $i++) {
                $digit = (int)$decimalPart[$i];
                $result .= $nums[$digit];
            }
        }
        return $result;
    }
    /**
     * 清理字符串中的HTML标签
     *
     * @param string $str 原始字符串
     * @return string
     */
    public static function stripTags($str)
    {
        return strip_tags($str);
    }
    /**
     * 将字符串转换为安全文件名
     *
     * @param string $str 原始字符串
     * @param string $spaceReplacement 空格替换字符
     * @return string
     */
    public static function slug($str, $spaceReplacement = '-')
    {
        $str = strtolower(trim($str));
        $str = preg_replace('/[^a-z0-9\s-]/', '', $str);
        $str = preg_replace('/[\s-]+/', $spaceReplacement, $str);
        return trim($str, '-');
    }
    /**
     * 字符串反转(支持中文)
     *
     * @param string $str 原始字符串
     * @return string
     */
    public static function reverse($str)
    {
        $chars = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
        return implode('', array_reverse($chars));
    }
    /**
     * 判断字符串是否为回文
     *
     * @param string $str 要检查的字符串
     * @return bool
     */
    public static function isPalindrome($str)
    {
        $cleaned = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($str));
        return $cleaned === strrev($cleaned);
    }
    /**
     * 统计单词数量
     *
     * @param string $str 原始字符串
     * @return int
     */
    public static function wordCount($str)
    {
        $words = preg_split('/\s+/', trim($str));
        return count(array_filter($words));
    }
    /**
     * 将字符串转换为指定大小写
     *
     * @param string $str 原始字符串
     * @param string $case 大小写模式:upper, lower, ucfirst, ucwords
     * @return string
     */
    public static function toCase($str, $case = 'lower')
    {
        switch ($case) {
            case 'upper':
                return mb_strtoupper($str);
            case 'lower':
                return mb_strtolower($str);
            case 'ucfirst':
                return ucfirst($str);
            case 'ucwords':
                return ucwords($str);
            default:
                return $str;
        }
    }
}
// 使用示例
$result = StringHelper::startsWith('hello world', 'hello'); // true
$result = StringHelper::truncate('这是一个很长的字符串', 6); // 这是一个...
$random = StringHelper::random(10); // 随机字符串
$phone = StringHelper::maskPhone('13812345678'); // 138****5678
$slug = StringHelper::slug('Hello World! This is PHP'); // hello-world-this-is-php
$camel = StringHelper::snakeToCamel('user_name'); // userName
$chinese = StringHelper::hasChinese('你好world'); // true
?>

这个工具类包含以下常用功能:

PHP 字符串工具类函数

  1. 字符串检查:startsWith、endsWith、hasChinese
  2. 字符串截取:substr、truncate
  3. 随机生成:random
  4. 命名转换:camelToSnake、snakeToCamel
  5. 格式化处理:amountToChinese、maskPhone、slug
  6. 验证功能:isValidUrl、isValidEmail、isPalindrome
  7. 其他工具:reverse、wordCount、removeWhiteSpace等

你可以根据项目需要扩展或修改这些方法,所有方法都是静态的,可以直接调用,无需实例化对象。

抱歉,评论功能暂时关闭!