REGEXVAULTv2.0
Security/Password Formats
Verified Safe

bcrypt Hash Regex for PHP

/^\$2[ayb]\$([0-2][0-9]|3[0-1])\$[./A-Za-z0-9]{53}$/

What this pattern does

This page provides a well-structured, multi-part regular expression for matching bcrypt hash, 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
<?php
// bcrypt Hash
// ReDoS-safe | RegexVault — Security > Password Formats

define('BCRYPT_HASH_PATTERN', '/^\$2[ayb]\$([0-2][0-9]|3[0-1])\$[.\/A-Za-z0-9]{53}$/');

function validate_bcrypt_hash(string $input): bool {
    return (bool) preg_match(BCRYPT_HASH_PATTERN, $input);
}

// Example
var_dump(validate_bcrypt_hash("$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW")); // bool(true)

Test Cases

Matches (Valid)
Rejects (Invalid)
$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW$2b$12$short
$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy$2c$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31l
$1$N9qo8uLO$ickgx2ZMRZoMyeIjZAgcfl

When to use this pattern

This pattern is drawn from the Security > Password Formats 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

bcrypt truncates passwords at 72 bytes — passwords longer than 72 characters are equally secure but this surprises developers. Use a pre-hashing step (HMAC) if you need to support passwords longer than 72 bytes.

Technical Notes

Structure: $2a/2b/2y$ + cost (4-31) + $ + 22-char salt + 31-char hash (in a modified base64 alphabet using ./A-Za-z0-9). $2b is the canonical prefix; $2a is legacy (PHP), $2y is PHP 5.3.7+. Cost of 10-12 is standard; use 12+ for new systems.

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