如何使用 PHP 的 preg_match 来验证字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1029731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use PHP's preg_match to validate strings?
提问by OrangeRind
Please tell me how to use the various symbols used for expression matching in preg_matchfunction of PHP.
请告诉我如何使用preg_matchPHP函数中用于表达式匹配的各种符号。
Besides basic information, please give example for checking a valid e-mail address and a string that should not contain / : ; { } * &
除了基本信息,请举例检查一个有效的电子邮件地址和一个不应包含 / : 的字符串。{ } * &
回答by Fábio Antunes
Simple example.. Verifying $var which is a string verifying and checking for (a to z AND A to Z) characters.
简单示例.. 验证 $var 这是一个字符串,用于验证和检查(a 到 z 和 A 到 Z)字符。
<?php
$var = 'hello';
if (ereg("[a-zA-Z]", $var)) {
echo 'it was typed correctly';
} else {
echo 'it was not typed correctly';
}
?>
more regular expressions syntax exemples: http://www.regexlib.com/
更多正则表达式语法示例:http: //www.regexlib.com/
EDIT:
编辑:
if (ereg("^([0-9,a-z,A-Z]+)([.,_]([0-9,a-z,A-Z]+))*[@]([0-9,a-z,A-Z]+)([.,_,-]([0-9,a-z,A-Z]+))*[.]([0-9,a-z,A-Z]){2}([0-9,a-z,A-Z])?$", $email)) {
echo 'email ok';
} else {
echo 'email not ok';
}
Regards.
问候。
回答by Copas
Jeff Atwoodrecently had an article on his coding horror blogabout regular expressions. Check out "Regular Expressions for Regular Programmers".
Jeff Atwood最近在他的编码恐怖博客上发表了一篇关于正则表达式的文章。查看“常规程序员的正则表达式”。
回答by merkuro
To check for a valid mail you can either use build in functionality (filter_var()/FILTER_VALIDATE_EMAIL) or use nice ready to use libraries which are compliant to the current RFC. PHP : Parsing Email Adresses in PHP. For examples on preg_match()you can go to the php website and a full list regular expression options is available on Wikipedia. To learn about Regex I recommend "The Regex Coach".
要检查有效邮件,您可以使用内置功能(filter_var()/FILTER_VALIDATE_EMAIL)或使用符合当前 RFC 的现成可用的库。PHP:在 PHP 中解析电子邮件地址。有关preg_match() 的示例,您可以访问 php 网站,维基百科上提供了完整的正则表达式选项列表。要了解 Regex,我推荐“ The Regex Coach”。
回答by Sinan ünür
I know the question is about PHP, but my purpose is to illustrate the intricacies of email address validation: To check if an email address conforms to RFC 2822, you can use the Perl module Email::Address. Do take a look at the source of that module as well as the RFC.
我知道这个问题是关于 PHP 的,但我的目的是说明电子邮件地址验证的复杂性:要检查电子邮件地址是否符合RFC 2822,您可以使用 Perl 模块Email::Address。请查看该模块的来源以及 RFC。
回答by Sinan ünür
If I give $var = 'hello87%^$' also returning "it was typed correctly";
如果我给 $var = 'hello87%^$' 也返回“输入正确”;

