search
HomeBackend DevelopmentPHP TutorialPHP implements the method of regular regular verification helper public class

这篇文章主要介绍了PHP实现的常规正则验证helper公共类,结合完整实例形式分析了php针对常规的电话、手机、邮箱、账号等进行正则验证的操作技巧,需要的朋友可以参考下

主要代码功能: 弥补平时项目对于验证功能这块的不严谨。具体细分的常规验证, 手机号/电话/小灵通验证, 字符串长度区间合法验证, 邮箱验证, 使用正则验证数据.

/**
 *
 *
 * 常规验证helper公共类
 *
 *
 */
class CheckForm
{
  //手机号/电话/小灵通 验证
  public function Mobile_check($mobile,$type = array())
  {
    /**
    * 手机号码
    * 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
    * 联通:130,131,132,152,155,156,185,186
    * 电信:133,1349,153,180,189
    */
    $res[1]= preg_match('/^1(3[0-9]|5[0-35-9]|8[0-9])\\d{8}$/', $mobile);
    /**
    * 中国移动:China Mobile
    11   * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
    */
    $res[2]= preg_match('/^1(34[0-8]|(3[5-9]|5[017-9]|8[0-9])\\d)\\d{7}$/', $mobile);
    /**
    * 中国联通:China Unicom
    * 130,131,132,152,155,156,185,186
    */
    $res[3]= preg_match('/^1(3[0-2]|5[256]|8[56])\\d{8}$/', $mobile);
    /**
    * 中国电信:China Telecom
    * 133,1349,153,180,189
    */
    $res[4]= preg_match('/^1((33|53|8[09])[0-9]|349)\\d{7}$/', $mobile);
    /**
    * 大陆地区固话及小灵通
    * 区号:010,020,021,022,023,024,025,027,028,029
    * 号码:七位或八位
    */
    $res[5]= preg_match('/^0(10|2[0-5789]|\\d{3})-\\d{7,8}$/', $mobile);
    $type = empty($type) ? array(1,2,3,4,5) : $type;
    $ok = false;
    foreach ($type as $key=>$val)
    {
      if ($res[$val])
      {
        $ok = true;
      }
      continue;
    }
    if ( $mobile && $ok )
    {
      return true;
    } else{
      return false;
    }
  }
  //字符串长度区间合法验证
  public function Strlength_check($str, $min=NULL, $max=NULL)
  {
    preg_match_all("/./u", $str, $matches);
    $len = count($matches[0]);
    if(is_null($min) && !empty($max) && $len < $max){
      return false;
    }
    if(is_null($max) && !empty($min) && $len > $min){
      return false;
    }
    if ($len < $min || $len > $max) {
      return false;
    }
    return true;
  }
  //邮箱验证
  public static function isEmail($str)
  {
    if (!$str) {
      return false;
    }
    return preg_match(&#39;#[a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+#is&#39;, $str) ? true : false;
  }
  /**
  * 使用正则验证数据
  * @access public
  * @param string $rule 验证规则
  * @param string $value 要验证的数据
  * @return boolean
  */
  public function regex($rule,$value) {
    $validate = array(
    //字段必须,不能为空
    &#39;require&#39; => &#39;/\S+/&#39;,
    //邮箱验证
    &#39;email&#39;  => &#39;/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/&#39;,
    //url验证
    &#39;url&#39;  => &#39;/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\&#39;:+!\.#\w]*)?$/&#39;,
    //货币验证
    &#39;currency&#39; => &#39;/^\d+(\.\d{0,2})?$/&#39;,
    //数字验证
    &#39;number&#39; => &#39;/^[-\+]?\d+(\.\d+)?$/&#39;,
    //zip验证
    &#39;zip&#39;  => &#39;/^\d{6}$/&#39;,
    //整数验证
    &#39;integer&#39; => &#39;/^[-\+]?\d+$/&#39;,
    //浮点数验证
    &#39;double&#39; => &#39;/^[-\+]?\d+(\.\d+)?$/&#39;,
    //英文验证
    &#39;english&#39; => &#39;/^[A-Za-z]+$/&#39;,
    &#39;gt0&#39; => &#39;/^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/&#39;,
    //合法帐号
    &#39;account&#39; => &#39;/^[a-zA-Z][a-zA-Z0-9_]{1,19}$/&#39;
    );
    // 检查是否有内置的正则表达式
    if(isset($validate[strtolower($rule)]))
    $rule = $validate[strtolower($rule)];
    return preg_match($rule,$value)===1;
  }
  function CheckPwd($pwd,$min=NULL, $max=NULL)
  {
  if (strlen($pwd)>$max || strlen($pwd)<$min || preg_match("/^\d*$/",$pwd) || preg_match("/^[a-z]*$/i",$pwd))
  {
    return false;
  }
  return true;
  }
}

is_null() 检测变量是否为 NULL。

以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

php遍历解析xml字符串的方法_php技巧

PHP递归遍历多维数组实现无限分类的方法_php技巧

php简单复制文件的方法_php技巧

The above is the detailed content of PHP implements the method of regular regular verification helper public class. 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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool