Miljankg
Miljankg

Reputation: 37

Redact characters in a phone number after showing first two digits

I have this regexp:

/(.*)(([0-9]([^a-zA-Z])*){7,}[0-9])(.*)/.

Given the following values

0654535263
065453-.-5263
065asd4535263

Expected Results

06**** 
06****
06****

Actual Results

0654535263
06****
065asd4535263

It does not match the last row because of the letters (I want to match from 0-3 letters) and it matches only last occurence (in the second row in example, it skips first row).

First of all thank u all oyur answers are very helpfull and i owe u a bih time. I cant create array of numbers and mask them like that because i can have string like this:

I am John, I live bla bla my phone is: 0, 6, 5, 4, 5, 3, 5, 2, 6 - 3 -- 065asd4535263.

To simplify i want to hide entered mobile number.

I had two problems:

  1. change regxp mentioned above, to hide digits separated by no more than 3 chars.
  2. preg_replace was replacing only one occurence.

At the end, I just need regexp to replace any array of digits, at least 6 digits long, separated by any number of special chars (12--654-5, 453/--222, 23....5645 etc) OR no more than 3 chars (ltters) (06asd453, 123as562).

Upvotes: -1

Views: 121

Answers (3)

Aust
Aust

Reputation: 11622

I'm guessing that the reason you want to use regular expressions is so that you don't mask every string that you get. This regex checks that there is at least 2 digits in the beginning of the string, then 0 to 3 alphabet characters, and then all the rest of the characters of the string need to be non-alphabet characters. If it matches, it masks the string, otherwise it says the string does not match.

$string = '0654535263';
if(preg_match('~^(\d{2})\d*?[a-zA-Z]{0,3}[^a-zA-Z]*$~', $string))
  $answer = preg_replace('~^(\d{2})\d*?[a-zA-Z]{0,3}[^a-zA-Z]*$~', '$1****', $string);
else
  $answer = $string . ' does not match';
print_r($answer); // 06****

Upvotes: 1

Baba
Baba

Reputation: 95161

You can just use substr_replace

 echo substr_replace($v, "****", 2);

Example

$list = array("0654535263","065453-.-5263","065asd4535263");
echo "<pre>";
foreach ( $list as $v ) {
    echo substr_replace($v, "****", 2), PHP_EOL;
}

Output

06****
06****
06****

Upvotes: 2

Ren&#233; H&#246;hle
Ren&#233; H&#246;hle

Reputation: 27325

Hmm why so complicated when you only want to mascarade your string.

$input = '0654535263';
$input = substr($input, 0, 2);
$output = $input . '********';

Its a bit easier when you only want the first 2 characters of your string. Perhaps your solution had another sin. But this is a bit easier.

Upvotes: 3

Related Questions