我有这段代码可以检查电子邮件是否有效:
$email = "abc123@sdsd.com";
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex, $email)) {
echo $email . " is a valid email. We can accept it.";
} else {
echo $email . " is an invalid email. Please try again.";
}
假设我有下面的字符串:
<html>
<body>
<p>abc123@sdsd.com</p>
</body>
</html>
我如何检查该字符串是否包含电子邮件? (因为它不适用于上面的代码)
^
和$
是 anchor ,需要全字符串匹配。如果您取消它,它将匹配字符串中某处的电子邮件。
正则表达式演示:https://regex101.com/r/xI0bC2/1
PHP 使用(更新以存储找到的电子邮件):
<?php
$email = "<html>
<body>
<p>abc123@sdsd.com</p>
</body>
</html>";
$regex = '/[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})/';
if (preg_match($regex, $email, $email_is)) {
echo $email_is[0] . " is a valid email. We can accept it.";
} else {
echo $email . " is an invalid email. Please try again.";
}
PHP 演示:https://eval.in/618679