如何在特定子字符串之后编辑敏感子字符串


How to redact sensitive substring following a specific substring?

我继承了这个脚本,其中一些敏感信息存储在数据库中......我想在保存并在日志中显示之前用 ******** 替换它。

我正在使用PHP...敏感信息是一组随机生成的字符,例如:yYng6Ytzh(有时也可能包括!s 和 @'s)。

它始终遵循特定的子字符串Password: 例如:Password: yYng6Ytzh,并被存储在单个字符串中的其他文本包围。

例如:

$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

我一直在尝试各种preg_match()组合,preg_replace()包括带有偏移量的str_replace (),但我一无所获。

谁能指出我正确的方向?

您可以匹配密码,然后使用后看检查" Password: "是否位于其前面:

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

编辑:我不得不将量词移到后面。这意味着您需要在使用之前对匹配进行左修剪。

您也可以使用命名组来匹配它。它更干净一点,imo。

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

您可以尝试以下解决方案:

$string = preg_replace_callback('#(?<=Password: )([^ ]+)#', function($match) {
                                                                return str_repeat('*', strlen($match[1]));
                                                            }, 'Password: yYng6Ytzh');
var_dump($string);
最好不仅

要编辑密码,还要取消原始密码的长度与替换文本的长度的关联。 与其使用星号,我会使用[redacted]. 虽然您知道有一个可预测的字符范围(字母数字加 @! ),但我认为保持正则表达式的这一部分超紧密没有任何优势。 使用非空格字符'S就可以了,并保持模式较小。 不要使用环视或捕获组,只需使用 'K 来忘记匹配的Password: 子字符串。

代码:(演示)

$email = <<<TEXT
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
TEXT;
echo preg_replace('~Password: 'K'S+~', '[redacted]', $email);

输出:

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: [redacted] Some more bla bla Kind Regards, Admin