search
HomeBackend DevelopmentPHP TutorialPublic methods of PHP development examples [detailed code explanation]

When we step into the ranks of PHP development, we must always ask ourselves, keep learning, and keep summarizing. Only in this way can we go further and further on the road of PHP development. Today, Based on personal development examples, we have summarized some common common public methods to allow novice partners to carry out development practice activities faster during the development process:

1. Use the public method msubstr to intercept the Chinese string. If it is too long, use an ellipsis instead:

Usage scenarios:

Using this type of public method usually involves uploading some article data to the editor in the background, and the corresponding data needs to be displayed on the front end. Sometimes, When the background data is too long and the space displayed on the front end is not enough to display all the data, the redundant parts are replaced with ellipsis, which can make the front-end data display beautiful and simple, giving people a pleasing feeling.

Code display:

/**
 * 截取中文字符串,过长的使用省略号代替
 */
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=.+?[&#39;|\"]/i",&#39;&#39;,$str);//去除样式  
    $str = preg_replace("/class=.+?[&#39;|\"]/i",&#39;&#39;,$str);//去除样式  
    $str = preg_replace("/id=.+?[&#39;|\"]/i",&#39;&#39;,$str);//去除样式     
    $str = preg_replace("/lang=.+?[&#39;|\"]/i",&#39;&#39;,$str);//去除样式      
    $str = preg_replace("/width=.+?[&#39;|\"]/i",&#39;&#39;,$str);//去除样式   
    $str = preg_replace("/height=.+?[&#39;|\"]/i",&#39;&#39;,$str);//去除样式   
    $str = preg_replace("/border=.+?[&#39;|\"]/i",&#39;&#39;,$str);//去除样式   
    $str = preg_replace("/face=.+?[&#39;|\"]/i",&#39;&#39;,$str);//去除样式   
    $str = preg_replace("/face=.+?[&#39;|\"]/",&#39;&#39;,$str);//去除样式只允许小写正则匹配没有带 i 


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


        return $suffix ? $slice.$fix : $slice;
}

2.enctype encryption :

Usage scenarios:

Front-end password matching setting rules or re-encryption of back-end password matching rules to prevent other hackers from using common passwords The matching mechanism performs tasks such as website shutdown.

Code display:

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

Note:

C('MD5_SUFFIX') project is a constant for reading configuration "MD5_SUFFIX", the constant can be set by yourself.

3. Replace the middle 4 digits of the mobile phone number with *

Usage scenario:

After a user registers an account with a mobile phone number on the website, in order to protect the user's information security, replace the middle 4 digits of the mobile phone number with *, which will prevent the mobile phone number from being displayed completely, thus ensuring the user's information security to a certain extent.

Code display:

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

4. Verify that the mobile phone number is correct:

Usage scenario:

Verify whether the mobile phone number filled in by the user is correct when the user registers the website, which facilitates the later maintenance of the data by our backend staff.

Code display:

/**
* 验证手机号是否正确
* @author honfei
* @param number $mobile
*/
function isMobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match(&#39;#^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}$#&#39;, $mobile) ? true : false;
}

5. Verify whether the input content is pure numbers:

Usage scenario:

Verification work when the user submits parameters that must be numeric items. After verification, corresponding feedback information can be given to the user to help the user submit data. effectiveness.

Code display:

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

6. Verify that the email is correct:

Usage scenarios:

When a user registers or binds email information, it is necessary to verify the true validity of the email, so that when users retrieve their password later, they can quickly and effectively receive the corresponding verification code.

Code display:

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

7. Recursive reordering of infinite classification arrays:

Usage scenarios:

Mall classification usually uses this method, which can effectively read and display the data of the mall classification, convenient for personal maintenance, and at the same time convenient for users. experience.

Code display:

//递归重新排序无限极分类数组
function recursive($array,$pid=0,$level=0){

//接收传递过来的数组
$arr = array();

foreach ($array as  $value) {

if($value[&#39;pid&#39;] == $pid){

//定义分类级别
$value[&#39;level&#39;] = $level;

//定义分类分隔符号
$value[&#39;html&#39;] = str_repeat(&#39;-&#39;, $level);


//$arr[]来存储$value
$arr[] = $value;


//array_merge():函数把一个或多个数组合并为一个数组。
$arr = array_merge($arr,recursive($array,$value[&#39;id&#39;],$level+1));

}
}

return $arr;

}

8. Get the IDs of all category subcategories:

Usage scenarios:

Rapid reading of mall categories can quickly integrate and display classified information data, while facilitating users’ quick access experience.

Code display:

//获取所有分类子分类的ID
function get_all_child($array, $id){

//定义一个数组
$arr = array();

//循环遍历
foreach ($array as $v) {

//判断pid是否等于id
if ($v[&#39;pid&#39;] == $id) {

//$arr接收所有的id
$arr[] = $v[&#39;id&#39;];

//array_merge():函数把一个或多个数组合并为一个数组。
$arr = array_merge($arr, get_all_child($array, $v[&#39;id&#39;]));

}
}

return $arr;

}

The above is the detailed content of Public methods of PHP development examples [detailed code explanation]. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools