


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

Undress AI Tool
Undress images for free

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

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

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

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



The official download portal of Aisi Assistant is located on the official website https://www.i4.cn/, and provides computer and mobile downloads, supporting device management, application installation, mode switching, screen projection and file management functions.

The entrance to the Little Red Book Dandelion can be accessed through the mobile app or computer. 1. Mobile: Open Xiaohongshu App, log in to an account that has completed real-name authentication, click "Me" to enter the personal center, find "Creation Center" or "Cooperation Center", click "More Services" and select "Blogger Cooperation" or "Dandelion Member" to enter; 2. Computer: Visit the official website https://in.xiaohongshu.com/, click "Login" in the upper right corner, and use the certified creator account to authorize login. The system automatically identifies the identity and enters the corresponding interface. New users need to submit their identity certificates, business licenses and other materials to complete their entry. The platform provides functions such as data analysis, blogger screening, cooperation management, content delivery and heating, and supports multiple cooperation modes.

The latest version of Google Earth online access is https://earth.google.com/web/, which supports global high-definition satellite images, 3D terrain, street panorama and historical image backtracking. It can operate smoothly in the browser without downloading, and can synchronize collection and custom landmarks through your account.

Xuanshu.com's reading link is https://www.xswang.com. The platform provides clearly classified novel resources, covering mainstream themes such as fantasy and cities, supports personalized reading settings and progress synchronization, and has a comment area and author interaction function to improve user reading experience.

Usefilter_var()tovalidateemailsyntaxandcheckdnsrr()toverifydomainMXrecords.Example:$email="user@example.com";if(filter_var($email,FILTER_VALIDATE_EMAIL)&&checkdnsrr(explode('@',$email)[1],'MX')){echo"Validanddeliverableemail&qu

The safe download link of Aisi Assistant is https://www.i4.cn/. The official website provides iOS and computer downloads, integrated device detection, application management, file transfer, system cleaning and other functions, and supports cross-platform data synchronization and a variety of auxiliary tools.

TherealclientIPinPHPcanberetrievedusingaprioritizedcheckofHTTPheaderslikeHTTP_CLIENT_IP,HTTP_X_FORWARDED_FOR,andHTTP_X_REAL_IP,fallingbacktoREMOTE_ADDR,withvalidationtopreventspoofing.

To start the session, you need to call session_start(); 2. Use $_SESSION to store data such as $_SESSION['username']='john_doe'; 3. Before cross-page access, you need to call session_start() and check the existence of variables; 4. Use unset() to delete a single session, and session_destroy() clear all data.
