Skip to content
Advertisement

How to redact sensitive substring following a specific substring?

I’ve inherited this script where some sensitive information is stored in the database…and I’m wanting to replace it with ******** before it gets saved and presented in a log.

I’m using PHP…and the sensitive information is a randomly generated set of characters eg: yYng6Ytzh (sometimes it may also include !’s and @’s).

It always follows the specific substring Password: eg: Password: yYng6Ytzh and is surrounded by other text stored in a single string.

For example:

$EmailContent 'Dear Some Name,

here is your password
...or click the link to login... 
someurl.com?action=Log%20In&username=someuser@test.com&…
Your log in details are:
Username: your full email address (where this email was received)
Password: yYng6Ytzh
Some more bla bla

Kind Regards,
Admin

I’ve been trying all sorts of combinations of preg_match(), preg_replace() including str_replace () with an offset, but I’m not getting anywhere.

Can anyone point me in the right direction please?

Advertisement

Answer

You can match the password and then use a look-behind to check that “Password:” is in-front of it:

/(?<=Password:)s*[a-zA-Z0-9!@]+/

Edit: I had to move the quantifier outside the look-behind. This means that you need to left trim the match before using it.

You could also match it using a named group. It is a little cleaner, imo.

/(?<=Password:)s*(?P<password>[a-zA-Z0-9!@]+)/
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement