Regular Expressions in PHP
From the PHP cheat sheet · Advanced Features · verified Jul 2026
Regular Expressions
Pattern matching with regex
php
// Match pattern
if (preg_match('/\d+/', $text, $matches)) {
echo $matches[0]; // First match
}
// Match all
preg_match_all('/\w+/', $text, $matches);
// Replace
$result = preg_replace('/\s+/', ' ', $text);
// Split
$parts = preg_split('/[,;]/', $text);💡 Use preg_quote() to escape user input in patterns
⚡ Named groups make matches more readable
📌 Add pattern modifiers: i (case), m (multiline), s (dotall)
🔥 preg_replace_callback for complex replacements