How To Replace Some Characters With Asterisks in PHP

How To Replace Some Characters With Asterisks in PHP

In this post, i will tell you how to remove some characters with asterisks in PHP.

In some situation you want to hide some characters for security reasons.

For example, if you ever noticed you receive email from bank then you will see some characters of your bank account is removed with asterisks or with any other special characters.

Other example, when you withdraw some amount from atm then you will get a reciept against transaction then you will see they don't show full card number on reciept because of some security reasons and make you safe from scammers.

In this post, i will give you three example :

Replace Some Characters With asterisks for mails :
  1. <?php
  2. function hide_mail($email) {
  3. $mail_part = explode("@", $email);
  4. $mail_part[0] = str_repeat("*", strlen($mail_part[0]));
  5. return implode("@", $mail_part);
  6. }
  7. echo hide_mail("info@expertphp.in");
Replace Some Characters With asterisks for phone numbers :
  1. <?php
  2. function hide_mobile($mobile) {
  3. return substr($mobile, 0, -4) . "****";
  4. }
  5. echo hide_mobile("9999999999");
Replace all characters with asterisks except first and last characters :
  1. <?php
  2. function get_starred($str) {
  3. $str_length = strlen($str);
  4. return substr($str, 0, 1).str_repeat('*', $str_length - 2).substr($str, $str_length - 1, 1);
  5. }
  6. $my_string = 'Yourname';
  7. echo get_starred($my_string); //will give you output Y******e

Phone: (+91) 8800417876
Noida, 201301