Replace the php string with an asterisk or other characters (mobile phone number, ID card)

Source: Internet
Author: User
In php, replace the characters at the specified position in the string with asterisks. our function can be used to implement substr, preg_replace, substr_replace, and so on. I will respectively assign these three functions

In php, replace the characters at the specified position in the string with asterisks. our function can be used to implement substr, preg_replace, substr_replace, and so on. below we will introduce one instance for the three functions respectively, we mainly talk about the phone number and ID card.

Replace the phone number string with the asterisk code:

  1. $ Str = "15832818835 ";
  2. Echo substr ($ str,). '*****'. substr ($ str, 8, strlen ($ str); // retain the first and last three digits
  3. ?>
  4. // Or use regular expressions
  5. $ S = 'manager Wang of www .111cn.net: 13999312365 manager Li: 13588958741 ';
  6. $ S = preg_replace ('# (d {3}) d {5} (d {3 })#', '$ {1} ***** $ {2}', $ s );
  7. Echo $ s;
  8. // Manager Wang: 139 ***** 365 manager Li: 135 ***** 741
  9. ?>

Use the following code to replace the character in the middle of a string with an asterisk:

  1. Function half_replace ($ str ){
  2. $ Len = strlen ($ str)/2;
  3. Return substr_replace ($ str, str_repeat ('*', $ len), ceil ($ len)/2), $ len );
  4. }
  5. Echo half_replace ('test'), "n", half_replace ('tests'), "n", half_replace ('exceptions ');

Php id card number, the code is as follows:

  1. Echo strlen ($ idcard) = 15? Substr_replace ($ idcard, "*****", 8, 4) :( strlen ($ idcard) = 18? Substr_replace ($ idcard, "*****",): "111cn.net indicates that the number of digits of the ID card is abnormal! ");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.