设为首页 收藏本站
查看: 257|回复: 0

[经验分享] PHP验证规则

[复制链接]

尚未签到

发表于 2017-3-20 14:44:09 | 显示全部楼层 |阅读模式
Regular ExpressionWill match...
fooThe string "foo"
^foo"foo" at the start of a string
foo$"foo" at the end of a string
^foo$"foo" when it is alone on a string
[abc]a, b, or c
[a-z]Any lowercase letter
[^A-Z]Any character that is not a uppercase letter
(gif|jpg)Matches either "gif" or "jpeg"
[a-z]+One or more lowercase letters
[0-9\.\-]Аny number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$Any word of at least one letter, number or _
([wx])([yz])wy, wz, xy, or xz
[^A-Za-z0-9]Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4})Matches three letters or four numbers
  Perl-Compatible Regular Expressions emulate the Perl syntax forpatterns, which means that each pattern must be enclosed in a pair ofdelimiters. Usually, the slash (/) character is used. For instance,/pattern/.
  The PCRE functions can be divided in several classes: matching, replacing, splitting and filtering.
DSC0000.gif Back to top

Matching Patterns
  The preg_match()function performs Perl-style pattern matching on a string. preg_match()takes two basic and three optional parameters. These parameters are, inorder, a regular expression string, a source string, an array variablewhich stores matches, a flag argument and an offset parameter that canbe used to specify the alternate place from which to start the search:
preg_match ( pattern, subject [, matches [, flags [, offset]]])
  The preg_match()function returns 1 if a match is found and 0 otherwise. Let's search the string "Hello World!" for the letters "ll":
<?php
if (preg_match("/ell/", "Hello World!", $matches)) {
  echo "Match was found <br />";
  echo $matches[0];
}
?>
  The letters "ll" exist in "Hello", so preg_match()returns1 and the first element of the $matches variable is filled withthe string that matched the pattern. The regular expression in the nextexample is looking for the letters "ell", but looking for them withfollowing characters:
<?php
if (preg_match("/ll.*/", "The History of Halloween", $matches)) {
  echo "Match was found <br />";
  echo $matches[0];
}
?>
  Now let's consider more complicated example. The most popular use ofregular expressions is validation. The example below checks if thepassword is "strong", i.e. the password must be at least 8 charactersand must contain at least one lower case letter, one upper case letterand one digit:
<?php
$password = "Fyfjk34sdfjfsjq7";

if (preg_match("/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/", $password)) {
    echo "Your passwords is strong.";
} else {
    echo "Your password is weak.";
}
?>
  The ^ and $ are looking for something at the start and the end ofthe string. The ".*" combination is used at both the start and the end.As mentioned above, the .(dot) metacharacter means any alphanumericcharacter, and * metacharacter means "zero or more". Between aregroupings in parentheses. The "?=" combination means "the next textmust be like this". This construct doesn't capture the text. In thisexample, instead of specifying the order that things should appear,it's saying that it must appear but we're not worried about the order.
  The first grouping  is (?=.*{8,}). This checks if there are at least8 characters in the string. The next grouping (?=.*[0-9]) means "anyalphanumeric character can happen zero or more times, then any digitcan happen". So this checks if there is at least one number in thestring. But since the string isn't captured, that one digit can appearanywhere in the string. The next groupings (?=.*[a-z]) and (?=.*[A-Z])are looking for the lower case and upper case letter accordinglyanywhere in the string.
  Finally, we will consider regular expression that validates an email address:
<?php
$email = firstname.lastname@aaa.bbb.com;
$regexp = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/";

if (preg_match($regexp, $email)) {
    echo "Email address is valid.";
} else {
    echo "Email address is <u>not</u> valid.";
}
?>
  This regular expression checks for the number at the beginning andalso checks for multiple periods in the user name and domain name inthe email address. Let's try to investigate this regular expressionyourself.
  For the speed reasons, the preg_match()function matchesonly the first pattern it finds in a string. This means it is veryquick to check whether a pattern exists in a string. An alternativefunction, preg_match_all(), matches a pattern against a string as many times as the pattern allows, and returns the number of times it matched.
Back to top

Replacing Patterns
  In the above examples, we have searched for patterns in a string, leaving the search string untouched. The preg_replace()function looks for substrings that match a pattern and then replaces them with new text. preg_replace()takes three basic parameters and an additional one. These parametersare, in order, a regular expression, the text with which to replace afound pattern, the string to modify, and the last optional argumentwhich specifies how many matches will be replaced.
preg_replace( pattern, replacement, subject [, limit ])
  The function returns the changed string if a match was found or anunchanged copy of the original string otherwise. In the followingexample we search for the copyright phrase and replace the year withthe current.
<?php
echo preg_replace("/([Cc]opyright) 200(3|4|5|6)/", "$1 2007", "Copyright 2005");
?>
  In the above example we use back references in the replacementstring. Back references make it possible for you to use part of amatched pattern in the replacement string. To use this feature, youshould use parentheses to wrap any elements of your regular expressionthat you might want to use. You can refer to the text matched bysubpattern with a dollar sign ($) and the number of the subpattern. Forinstance, if you are using subpatterns, $0 is set to the whole match,then $1, $2, and so on are set to the individual matches for eachsubpattern.
  In the following example we will change the date format from "yyyy-mm-dd" to "mm/dd/yyy":
<?php
echo preg_replace("/(\d+)-(\d+)-(\d+)/", "$2/$3/$1", "2007-01-25");
?>
  We also can pass an array of strings as subjectto make thesubstitution on all of them. To perform multiple substitutions on thesame string or array of strings with one call to preg_replace(), we should pass arrays of patterns and replacements. Have a look at the example:
<?php
$search = array ( "/(\w{6}\s\(w{2})\s(\w+)/e",
                  "/(\d{4})-(\d{2})-(\d{2})\s(\d{2}:\d{2}:\d{2})/");

$replace = array ('"$1 ".strtoupper("$2")',
                  "$3/$2/$1 $4");

$string = "Posted by John | 2007-02-15 02:43:41";     

echo preg_replace($search, $replace, $string);?>
  In the above example we use the other interesting functionality -you can say to PHP that the match text should be executed as PHP codeonce the replacement has taken place. Since we have appended an "e" tothe end of the regular expression, PHP will execute the replacement itmakes. That is, it will take strtoupper(name) and replace it with theresult of the strtoupper()function, which is NAME.
Back to top

Array Processing
  PHP's preg_split()function enables you to break a stringapart basing on something more complicated than a literal sequence ofcharacters. When it's necessary to split a string with a dynamicexpression rather than a fixed one, this function comes to the rescue.The basic idea is the same as preg_match_all()except that,instead of returning matched pieces of the subject string, it returnsan array of pieces that didn't match the specified pattern. Thefollowing example uses a regular expression to split the string by anynumber of commas or space characters:
<?php
$keywords = preg_split("/[\s,]+/", "php, regular expressions");
print_r( $keywords );
?>
  Another useful PHP function is the preg_grep()functionwhich returns those elements of an array that match a given pattern.This function traverses the input array, testing all elements againstthe supplied pattern. If a match is found, the matching element isreturned as part of the array containing all matches. The followingexample searches through an array and all the names starting withletters A-J:
<?php
$names = array('Andrew','John','Peter','Nastin','Bill');
$output = preg_grep('/^[a-m]/i', $names);
print_r( $output );
?>

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-352568-1-1.html 上篇帖子: PHP学习笔记<1> 下篇帖子: PHP String Functions
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表