


Public 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=.+?['|\"]/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 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('MD5_SUFFIX')); }
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('#^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. 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('/^\d+$/i', $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 = '/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/'; 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['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 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['pid'] == $id) { //$arr接收所有的id $arr[] = $v['id']; //array_merge():函数把一个或多个数组合并为一个数组。 $arr = array_merge($arr, get_all_child($array, $v['id'])); } } 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
