如何将 PHP 的 eregi 更改为 preg_match
可能的重复:
如何在 PHP 中将 ereg 表达式转换为 preg?< /a>
我需要帮助,下面是一个非常基本的小正则表达式,用于在某种程度上验证电子邮件,我确实意识到它的效果不是最好的,但对于我的需要来说,目前还可以。
它目前使用 PHP 的 eregi 函数,php.net 说它现在是一个已弃用的函数,我应该使用 preg_match 代替,简单地用 preg_match 替换 erei 是行不通的,有人可以告诉我吗如何让它发挥作用?
function validate_email($email) {
if (!eregi("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$", $email)) {
echo 'bad email';
} else {
echo 'good email';
}
}
function validate_email($email) {
if (!preg_match("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$", $email)) {
echo 'bad email';
} else {
echo 'good email';
}
}
Possible Duplicate:
How can I convert ereg expressions to preg in PHP?
I need help, below is a small VERY basic regex to somewhat validate an email, I do realize it does not work the greatest but for my needs it is ok for now.
It currently uses PHP's eregi function which php.net says is now a depreciated function and I should use preg_match instead, simply replacing erei with preg_match does not work, can someone show me how to make it work?
function validate_email($email) {
if (!eregi("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$", $email)) {
echo 'bad email';
} else {
echo 'good email';
}
}
function validate_email($email) {
if (!preg_match("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$", $email)) {
echo 'bad email';
} else {
echo 'good email';
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Perl 风格的正则表达式模式始终需要分隔。字符串中的第一个字符被认为是分隔符,所以像这样:
您最初的尝试不起作用的原因是因为它试图使用
^
作为分隔符,但(显然)发现正则表达式末尾没有匹配的^
。Perl-style regex patterns always need to be delimited. The very first character in the string is considered the delimiter, so something like this:
The reason your initial attempt didn't work is because it was trying to use
^
as the delimiter character but (obviously) found no matching^
for the end of the regex.您需要更改三件事,
i
标志。否则,其余部分看起来与 PCRE 兼容(是的,这有点多余 =P)
You will need to change three things
i
flag.Otherwise, the rest looks PCRE compatible (yes, that's kind of redundant =P)