2

I need to censor email addresses when a certain page is viewed so that the first letter is visible and the @ sign is visible, but the rest is censored using a * like the example below:

v********@*********

How would I go about doing this? I can't find any answers to this (or maybe I'm just not googling the right thing).

VenomRush
  • 1,622
  • 3
  • 15
  • 25
  • This seems a little specific to find a ready to use script on Google. How would you do it if you wrote the script yourself? – Halcyon Jun 01 '17 at 09:38
  • with the loop method the link would be helpful https://stackoverflow.com/questions/8163746/how-to-replace-certain-parts-of-my-string – K.M Jun 01 '17 at 09:39
  • Well keeping the first character is easy using substr() but I don't know what regex I'd need to do the rest. An email address could have letters and numbers, but any regex I find doesn't prevent the @ symbol from being replaced. – VenomRush Jun 01 '17 at 09:41
  • 1
    If you want a regex you can use `/[^@]/` in a replace which matches anything but the `@`. – Jenne Jun 01 '17 at 09:45
  • maybe [this](http://php.net/manual/en/function.preg-replace.php) is what you need – hungrykoala Jun 01 '17 at 09:45

4 Answers4

4

Short and sweet one liner:

$result = substr($str, 0, 1) . preg_replace('/[^@]/', '*', substr($str, 1));
  1. substr($str, 0, 1) gets the first character of the string e.g. v.
  2. preg_replace('/[^@]/', '*', substr($str, 1)) replaces everything from the first character onwards that isn't an @ symbol.

eval.in demo.

Ethan
  • 4,295
  • 4
  • 25
  • 44
0
<?php

$email = "vmail@vmail.com";

// Split into name and domain
$pieces = explode("@", $email);

// Add the first letter
$censored = substr($email, 0, 1);

// Add the name stars
for ($i = 1; $i <= strlen($pieces[0]) - 1; $i++) {
    $censored = $censored."*";
}

// Add the @ sign
$censored = $censored."@";

// Add the domain stars
for ($i = 1; $i <= strlen($pieces[1]); $i++) {
    $censored = $censored."*";
}

echo $censored;
IAmCoder
  • 3,179
  • 2
  • 27
  • 49
0

With regex and str_pad?
Use regex to capture the first letter, then the rest in pieces.
Use str_pad to add the "*" in the string.

https://3v4l.org/dvYpT

$mail = "Test@test.com";

preg_match("/(.)(.*?)@(.*)/", $mail, $Match);

$str = $Match[1] . str_pad("", strlen($Match[2]), "*"). "@" . str_pad("", strlen($Match[3]), "*");
echo $str;
Andreas
  • 23,610
  • 6
  • 30
  • 62
0

Use a callback reassembling the string:

<?php
$subject = 'someone@example.com';
$subject = preg_replace_callback('/^(.)(.*)@(.*)$/', function($m) {
  return sprintf(
    '%s%s@%s',
    $m[1],
    str_pad('', strlen($m[2]), '*'),
    str_pad('', strlen($m[3]), '*')
  );
}, $subject);
var_dump($subject);

The output obviously is:

string(19) "s******@***********"
arkascha
  • 41,620
  • 7
  • 58
  • 90