Backend Development 8 min read

Common PHP Utility Functions for String Handling, Encryption, and Validation

This article presents a collection of practical PHP utility functions—including string truncation with ellipsis, MD5-based encryption, phone number masking, mobile, numeric and email validation, as well as recursive category handling—complete with usage scenarios and full source code to help developers quickly implement common backend tasks.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Common PHP Utility Functions for String Handling, Encryption, and Validation

When starting PHP development, continuous learning is essential; this article shares a set of native utility functions that help beginners accelerate their coding practice.

1. msubstr – Truncate Chinese strings and append an ellipsis when the text is too long. This is useful when backend data exceeds the display space on the frontend.

/
/**
 * 截取中文字符串,过长的使用省略号代替
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
    $str = preg_replace("/<a[^>]*>/i", "", $str);
    $str = preg_replace("/<\/a>/i", "", $str);
    $str = preg_replace("/<div[^>]*>/i", "", $str);
    $str = preg_replace("/<\/div>/i", "", $str);
    $str = preg_replace("/<!--[^>]*-->/i", "", $str);//注释内容
    $str = preg_replace("/style=.+?['|\"]/i", "", $str);//去除样式
    $str = preg_replace("/class=.+?['|\"]/i", "", $str);//去除样式
    $str = preg_replace("/id=.+?['|\"]/i", "", $str);//去除样式
    $str = preg_replace("/lang=.+?['|\"]/i", "", $str);//去除样式
    $str = preg_replace("/width=.+?['|\"]/i", "", $str);//去除样式
    $str = preg_replace("/height=.+?['|\"]/i", "", $str);//去除样式
    $str = preg_replace("/border=.+?['|\"]/i", "", $str);//去除样式
    $str = preg_replace("/face=.+?['|\"]/i", "", $str);//去除样式
    $str = preg_replace("/face=.+?['|\"]/", "", $str);//去除样式只允许小写正则匹配没有带 i

    if(function_exists("mb_substr")){
        $slice = mb_substr($str, $start, $length, $charset);
    } elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str, $start, $length, $charset);
    } else {
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
    }
    $fix = '';
    if(strlen($slice) < strlen($str)){
        $fix = '...';
    }
    return $suffix ? $slice.$fix : $slice;
}

2. enctype – Optimized MD5 encryption with a configurable suffix. Useful for adding an extra layer of hashing to passwords.

/
/**
 * 公共方法
 * 优化md5加密:
 */
function enctype($password) {
    return md5($password . C('MD5_SUFFIX'));
}

3. suohao – Mask the middle four digits of a phone number with asterisks. Enhances privacy when displaying user phone numbers.

/
/**
 * 将手机号中间4位替换为*
 */
function suohao($phone){
    $p = substr($phone,0,3)."****".substr($phone,7,4);
    return $p;
}

4. isMobile – Validate mobile phone numbers using a regular expression. Ensures that submitted numbers conform to common Chinese mobile formats.

/
/**
 * 验证手机号是否正确
 * @author honfei
 * @param number $mobile
 */
function isMobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
}

5. isNumeric – Check whether a given input consists solely of digits. Helpful for validating numeric parameters.

/
/**
 * 验证输入的内容是否为纯数字
 * @author wdy
 * @param number $mobile
 */
function isNumeric($number) {
    if (!is_numeric($number)) {
        return false;
    }
    return preg_match('/^\d+$/i', $number) ? true : false;
}

6. isEmail – Validate email addresses with a regular expression. Used during user registration or email binding.

/
/**
 * 验证邮箱是否正确
 * @author wdy
 * @param [email protected] $email
 */
function isEmail($email){  
    $mode = '/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/';  
    if(preg_match($mode,$email)){
        return true;
    }else{
        return false;
    }
}

7. recursive – Recursively reorder an infinite‑level category array, adding level and visual prefix. Suitable for e‑commerce category trees.

/
//递归重新排序无限极分类数组
function recursive($array,$pid=0,$level=0){
    //接收传递过来的数组
    $arr = array();
    foreach ($array as $value) {
        if($value['pid'] == $pid){
            //定义分类级别
            $value['level'] = $level;
            //定义分类分隔符号
            $value['html'] = str_repeat('-', $level);
            //$arr[]来存储$value
            $arr[] = $value;
            //array_merge():函数把一个或多个数组合并为一个数组。
            $arr = array_merge($arr, recursive($array, $value['id'], $level+1));
        }
    }
    return $arr;
}

8. get_all_child – Retrieve IDs of all descendant categories recursively. Enables fast aggregation of sub‑category data.

/
//获取所有分类子分类的ID
function get_all_child($array, $id){
    //定义一个数组
    $arr = array();
    //循环遍历
    foreach ($array as $v) {
        //判断pid是否等于id
        if ($v['pid'] == $id) {
            // $arr接收所有的id
            $arr[] = $v['id'];
            //array_merge():函数把一个或多个数组合并为一个数组。
            $arr = array_merge($arr, get_all_child($array, $v['id']));
        }
    }
    return $arr;
}

These functions can be directly integrated into PHP projects to streamline common backend operations such as text truncation, data masking, input validation, and hierarchical data processing.

backendvalidationphpencryptionutility functionsstring-manipulation
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.