Database Connection String with Credentials Regex for PHP
/^(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|mssql|sqlserver|mariadb|oracle):\/\/([^:]+):([^@]+)@([^/?]+)(?:\/([^?]+))?(?:\?(.+))?$/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching database connection string with credentials, 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
// Database Connection String with Credentials
// ReDoS-safe | RegexVault — Security > Secrets & Config
define('DATABASE_CONNECTION_STRING_WITH_CREDENTIALS_PATTERN', '/^(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|mssql|sqlserver|mariadb|oracle):\\/\\/([^:]+):([^@]+)@([^\/?]+)(?:\\/([^?]+))?(?:\?(.+))?$/');
function validate_database_connection_string_with_credentials(string $input): bool {
return (bool) preg_match(DATABASE_CONNECTION_STRING_WITH_CREDENTIALS_PATTERN, $input);
}
// Example
var_dump(validate_database_connection_string_with_credentials("postgresql://user:password@localhost:5432/mydb")); // bool(true)Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
postgresql://user:password@localhost:5432/mydb | postgresql://localhost:5432/mydb |
mysql://root:secret@db.example.com/app | ftp://user:pass@host/path |
mongodb+srv://admin:P%40ssw0rd@cluster.example.net/prod | postgresql://user:@localhost/db |
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
Connection strings in Heroku, Render, and Railway configs are often set as environment variables but may be hardcoded in old codebases or appear in error messages when logged. Never log connection strings.
Technical Notes
Capture groups: 1=scheme, 2=username, 3=password, 4=host:port, 5=database, 6=query params. Passwords may be URL-encoded (e.g., P%40ssw0rd). Extract and rotate any credentials found in this format in code or config files.
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