Generic Secret Assignment in Code Regex for PHP
/(?:password|passwd|secret|token|api[_-]?key|auth[_-]?key|access[_-]?key|client[_-]?secret|private[_-]?key|encryption[_-]?key)(?:[\s]*[:=][\s]*)["']([^"'\s]{8,})["']/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching generic secret assignment in code, ported and verified for PHP. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your PHP project — whether you're validating in a Laravel validator, a WordPress plugin, or a standalone PHP script.
Php Implementation
<?php
// Generic Secret Assignment in Code
// ReDoS-safe | RegexVault — Security > Secrets & Config
define('GENERIC_SECRET_ASSIGNMENT_IN_CODE_PATTERN', '/(?:password|passwd|secret|token|api[_-]?key|auth[_-]?key|access[_-]?key|client[_-]?secret|private[_-]?key|encryption[_-]?key)(?:[\s]*[:=][\s]*)["\']([^"\'\s]{8,})["\']/');
function validate_generic_secret_assignment_in_code(string $input): bool {
return (bool) preg_match(GENERIC_SECRET_ASSIGNMENT_IN_CODE_PATTERN, $input);
}
// Example
var_dump(validate_generic_secret_assignment_in_code("password = 'mySecretPassword123'")); // bool(true)Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
password = 'mySecretPassword123' | password = '' |
api_key = "AIzaSyD-9tSrke72I6e0qOZV" | api_key = variable_name |
token: 'eyJhbGciOiJIUzI1NiJ9' | // password might be here |
When to use this pattern
This pattern is drawn from the Security > Secrets & Config category and carries a ReDoS-safe certification. That matters for PHP developers because especially relevant in PHP where PCRE backtracking limits can trigger silent failures on malicious input. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
Effective secret scanning requires both pattern matching AND entropy analysis. Simple dictionary words that match the pattern are likely placeholders. Tools like TruffleHog and GitLeaks combine regex with Shannon entropy scoring.
Technical Notes
Detection pattern for secret scanning in codebases and config files. The value capture group (1) should be examined for entropy and length. False positive rate is non-trivial — values like 'your_password_here' or 'changeme' are common placeholders. Use entropy scoring alongside pattern matching.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern