PHP Regular Expressions

PHP Regular Expressions

Regular expressions are patterns for matching, searching, and manipulating strings. PHP uses PCRE (Perl-Compatible Regular Expressions).

1 - preg_match() — Test for Match

$email = "[email protected]";
if (preg_match("/^[\w.+-]+@[\w-]+\.[a-z]{2,}$/i", $email)) {
    echo "Valid email";
}

// Capture groups
preg_match("/(\d{4})-(\d{2})-(\d{2})/", "2024-05-01", $matches);
// $matches[0] = "2024-05-01"
// $matches[1] = "2024", [2] = "05", [3] = "01"

2 - preg_match_all() — Find All

$html = "<a>Link 1</a> <a>Link 2</a>";
preg_match_all("!<a>(.+?)</a>!", $html, $matches);
print_r($matches[1]); // ["Link 1", "Link 2"]

3 - preg_replace() — Replace

$text = "Phone: 123-456-7890";
$clean = preg_replace("/\d/", "*", $text);
// "Phone: ***-***-****"

4 - preg_split()

$parts = preg_split("/[\s,]+/", "one, two,  three  four");
// ["one", "two", "three", "four"]

5 - Common Patterns

/^\d{4}-\d{2}-\d{2}$/     // Date YYYY-MM-DD
/^[a-zA-Z0-9_]{3,20}$/    // Username
/^(?=.*[A-Z])(?=.*\d).{8,}$/ // Strong password
/^https?:\/\/.+/           // URL

Note: For email validation, prefer filter_var($email, FILTER_VALIDATE_EMAIL) over custom regex. For URLs, use FILTER_VALIDATE_URL. Regex is best for custom patterns the filter functions don't cover.

-Tip-