Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mask credit card number mask in a text?

I have a form on my website and my customers send message to me with this form. Sometimes they write their credit card number on the message. So this is really critical. I want to mask these credit card numbers. But of course card numbers don't come on a regular basis.

Example 1: 1111222233334444

Example 2: 4444 3333 2222 1111

Example 3: 4444-3333-2222-1111

Example 4: 4444 - 3333 - 2222 - 1111

Example 5: 4444--3333--2222--1111

So I can mask for example 1, 2 and 3. But if there are more than one space or dash between numbers I can't.

And this is my last regex:

preg_replace("/(?:\b| )([3456]\d{3})([ -]+){0,1}\d{4}([ -]+){0,1}\d{4}([ -]+){0,1}(\d{0})/", "$1********$2", $a1);

And results for this regex:

Result 1: 4444********1111

Result 2: 4444******** 1111

Result 3: 4444********-1111

Result 4: 4444******** - 1111

Result 5: 4444********--1111

So what should I do in regex? Thanks.

like image 942
Mahmut Tuncer Avatar asked Jan 03 '23 10:01

Mahmut Tuncer


1 Answers

May I suggest that you separate validation of your credit card number from the presentation of that number to your users via the UI? Assuming you have only stored valid credit card numbers, then it is probably safe to assume that every number has at least 8 digits. If so, then you can just use a blanket regex to only display the first 4 and last 8 digits:

$cc = "4444--3333--2222--1111";
echo preg_replace("/(\d{4}).*(\d{4})/", "$1********$2", $cc);

4444********1111

Demo

You might point out that this puts the same number of stars in between every card number. But, then again, this is a good thing, because it makes it even harder for a snooper to fish out what the real unmasked number actually is.

Edit:

Here is a smarter regex which will star out the middle portion of any number, leaving only the first and last 4 characters visible:

$cc = "4444--3333--2222--1111";
echo preg_replace("/(?<=.{4}).(?=.{4})/", "*", $cc);

4444**************1111

Note that this solution would not remove anything from 11114444 as a theoretical input.

like image 162
Tim Biegeleisen Avatar answered Jan 04 '23 22:01

Tim Biegeleisen