Bujji Bujji - 6 months ago 11
SQL Question

Replacing certain characters in email addresses with '*' in an SQL query

I am trying to implement similar feature in my website and wanted to display email like below .

enter image description here

Below is the MYSQL code I have written and it is working OK for the scenarios I tested . But wanted to check with you guys if we have any better solution for this .

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


Thanks for your help

Regards
Kiran

Answer

As stated in my comment, I would recommend a PHP-based solution like this:

<?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;
?>