phpregexlookbehind

Find the username and password in a request header and sensor it


I'm receiving a complete request header from a third party. I need to hide the password and username.

Php-Auth-Pw:     p@ssword
Php-Auth-User:   testuser

How can I make it to look like this

Php-Auth-Pw:     ******
Php-Auth-User:   ******

I don't fully understand regular expressions just yet, and I've just read something about lookbehinds.

I've found this;

(?<=\Php-Auth-Pw:\s)(\w+)
(?<=\Php-Auth-User:\s)(\w+)

But what would be the correct way to do this with the PHP flavor?


Solution

  • You may replace them with a single call to preg_replace:

    $s = preg_replace('~\bPhp-Auth-(?:Pw|User):\s*\K\S+~', '******', $s);
    

    See the regex demo

    Details: