在SQL查询中用'*'替换电子邮件地址中的某些字符

时间:2012-02-07 15:16:47

标签: mysql sql

我正在尝试在我的网站中实现类似的功能,并希望显示如下的电子邮件。

enter image description here

下面是我编写的MYSQL代码,它对我测试的场景工作正常。但是,如果我们有更好的解决方案,想与你们联系。

SELECT CONCAT(RPAD(CONCAT(RPAD(firstletter, firstpartlength - 2, '*'),
                   beforedomain), (
                            secondpartlength - Length(afterdot) +
                            firstpartlength ),
                     '*'), afterdot) hiddenemail
FROM   (SELECT SUBSTRING(email, 1, 1)                             firstletter,
               SUBSTRING(email, INSTR(email, '@') - 1, 3)         beforedomain,
               SUBSTR(SUBSTRING(email, INSTR(email, '@')),
               INSTR(SUBSTRING(email,
                     INSTR(email, '@')), '.'))
                      afterdot,
               LENGTH(SUBSTRING(email, 1, INSTR(email, '@') - 1))
               firstpartlength,
               LENGTH(SUBSTRING(email, INSTR(email, '@') + 1))
               secondpartlength
        FROM   test_table) a 

感谢您的帮助

此致 基兰

2 个答案:

答案 0 :(得分:2)

没有多项选择的简单解决方案:

SELECT
CONCAT(
    SUBSTR(`email`,1,1),
    REPEAT('*',LOCATE('@',`email`)-3),
    SUBSTR(`email`,LOCATE('@',`email`)-1,3),
    REPEAT('*',LENGTH(`email`)-LOCATE('.',REVERSE(`email`))-LOCATE('@',`email`)-1),
    SUBSTR(`email`,LENGTH(`email`)-LOCATE('.',REVERSE(`email`)))
) 
FROM `accounts`;

答案 1 :(得分:1)

正如我的评论中所述,我建议使用基于PHP的解决方案:

<?php
$email = 'youremail@ddre.ss';

$beforeAt=explode("@",$email);
$beforeAt=$beforeAt[0];
$asterisks=str_repeat("*",strlen($beforeAt)-2);
$beforeAt=$beforeAt{0}.$asterisks.substr($beforeAt,-1);
$domain=explode("@",$email);
$domain=explode(".",$domain[1]);
$extension=$domain[count($domain)-1];
$domain=implode(".",$domain);
$domain=substr($domain,0,-1*strlen($extension)-1);
$asterisks=str_repeat("*",strlen($domain)-1);
$email=$beforeAt."@".substr($domain,0,1).$asterisks.".".$extension;

echo $email;
?>