PHP Regex Best Practices
Use named groups, validate with existing filter functions when possible, test patterns online, and never use regex for HTML parsing.
Use named groups, validate with existing filter functions when possible, test patterns online, and never use regex for HTML parsing.
<?php
// DO: Use PHP built-ins for common validation
filter_var($email, FILTER_VALIDATE_EMAIL);
filter_var($url, FILTER_VALIDATE_URL);
filter_var($ip, FILTER_VALIDATE_IP);
// DO: Name your capture groups
$pattern = "/(?P<year>\d{4})-(?P<month>\d{2})/";
// DO: Compile reusable patterns as constants
const EMAIL_PATTERN = "/^[^@\s]+@[^@\s]+\.[^@\s]+$/i";
// NEVER: Parse HTML with regex
// preg_match("/<title>(.+)<\/title>/is", $html, $m); // fragile!
// DO: Use DOMDocument for HTML parsing
$dom = new DOMDocument();
@$dom->loadHTML($html);
$titles = $dom->getElementsByTagName("title");
Never parse HTML with regex — use DOMDocument or a proper HTML parser like PHP's built-in DOM extension.