使用 PHP 使用包含电子邮件地址的查询字符串验证 URL



嗨,我对包含电子邮件地址的查询字符串进行正确的 url 验证时遇到问题,例如:

https://example.com/?email=john+test1@example.com

此电子邮件是 OFC 正确的john+test1@example.comjohn@example.com的别名

我有这样的正则表达式:

$page = trim(preg_replace('/[\0\s+]/', '', $page));

但它没有像我预期的那样工作,因为它+替换了空字符串出了什么问题。它应该将此+保留为电子邮件地址的别名,并应删除特殊字符,同时保持地址的正确性。

带有+的错误网址示例:

https://examp+le.com/?email=example@exam+ple.com

查询字符串中没有电子邮件的其他 URL 应使用此正则表达式正确验证

知道如何解决吗?

我认为这就是你要找的:

<?php
function replace_plus_sign($string){
return
preg_replace(
'/#/',
'+',
preg_replace(
'/++/i',
'',
preg_replace_callback(
'/(email([d]+)?=)([^@]+)/i',
function($matches){
return $matches[1] . preg_replace('/+(?!$)/i', '#', $matches[3]);
},
$string
)
)
);
}
$page = 'https://exam+ple.com/email=john+test1+@example.com&email2=john+test2@exam+ple.com';
echo replace_plus_sign($page);

提供以下输出:

https://example.com/email=john+test1@example.com&email2=john+test2@example.com

起初,我用#替换了有效的+登录电子邮件地址,然后删除了所有剩余的+,之后,我用+替换了#

如果 URL 上有#,则此解决方案将不起作用,因此您需要使用另一个字符而不是#作为临时替换。

最新更新