Lesson

PHP RegEx

10 min reading
Free Course

PHP RegEx: Pattern Matching with PCRE Functions

PHP RegEx (regular expressions) lets you search, validate, extract, and replace text with a compact pattern instead of long chains of string functions. PHP uses the PCRE engine (Perl Compatible Regular Expressions) and exposes it through the preg_* functions. This guide covers the core functions, how to write patterns that validate input correctly, and the mistakes that cause wrong matches, security problems, and slow code.

What Is PHP RegEx?

A regular expression is a pattern string that describes a set of texts. In PHP, the pattern is written inside delimiters, which are characters that mark where the pattern starts and ends. Forward slashes are the most common choice, as in /pattern/, but you can use others, such as #pattern# or ~pattern~.

Anything after the closing delimiter is a modifier (a flag), such as i for case-insensitive matching.

'/hello/i'   // pattern: hello, modifier: i

The preg_ prefix stands for PCRE. The older ereg_* functions were removed in PHP 7, so preg_* is the one to use.

Core PHP Regex Functions

PHP provides three primary functions that cover almost every text-matching task.

  • preg_match($pattern, $subject, $matches): Checks if a pattern exists and captures the first match. Returns 1 on match, 0 on no match, or false on error.

  • preg_match_all($pattern, $subject, $matches): Finds every occurrence in the string and stores all captured groups.

  • preg_replace($pattern, $replacement, $subject): Replaces matched patterns with a new string.

<?php
declare(strict_types=1);

$username = "dev_sadia99";
$isValidUsername = preg_match('/^[a-zA-Z][a-zA-Z0-9_]{3,19}$/', $username) === 1;

$logLine = "Orders: #1042, #1049, #1088";
preg_match_all('/#(\d+)/', $logLine, $orderMatches);

$rawPhone = "(555) 234-8910";
$digitsOnly = preg_replace('/\D+/', '', $rawPhone);

echo "Valid username: " . ($isValidUsername ? "Yes" : "No") . PHP_EOL;
print_r($orderMatches[1]);
echo "Digits only: {$digitsOnly}" . PHP_EOL;

Writing Safe, Readable Patterns

Add the i modifier after the closing delimiter for case-insensitive matching, and u for UTF-8 Unicode support. For complex patterns with slashes (such as URLs), switch delimiters to ~ so you do not have to escape every /.

How to Check That Your Regex Works

  1. Test every pattern with inputs that should match, inputs that should not, and edge cases such as an empty string, a trailing newline, Unicode letters, and very long strings.

  2. Use var_dump() to see the real return value (1, 0, or false).

  3. Check preg_last_error_msg() whenever you get false.

  4. Print $matches with print_r() to see which group holds which text.

  5. For URLs and long patterns, build them in small pieces and test each piece.

Common Mistakes to Avoid

  • Forgetting ^ and $ anchors when validating: Without ^ and $, /[0-9]{4}/ matches "abc1234xyz" because the pattern exists inside the string.

  • Using regex to parse full HTML or emails: Use DOMDocument for HTML and filter_var($email, FILTER_VALIDATE_EMAIL) for emails instead of fragile regexes.

  • Writing catastrophic backtracking patterns: Nested quantifiers like /(a+)+$/ can freeze your server on malformed input. Keep quantifiers specific.

Conclusion

PHP RegEx is powerful when you keep patterns small and anchored. Use preg_match() with === 1, preg_match_all() for every match, and preg_replace() or preg_replace_callback() for replacements. Escape user input withpreg_quote(), add u for Unicode, use DOMDocument and filter_var() where regex is the wrong tool, and test with awkward input.

Frequently Asked Questions

What happens if user input is placed directly inside a regex pattern?

Characters like., *, and / change the meaning of the pattern, and a bad value can make it invalid. Always escape dynamic strings with preg_quote($userString, '/') before interpolating them.

What does preg_split() do?

preg_split('/[\s,]+/', $text) Splits a string into an array using a regular expression as the delimiter. It is useful for splitting on spaces, tabs, and commas together.

Why did preg_match() return 1 instead of true?

preg_match() returns an integer: 1 for a match, 0 for no match, and false if the pattern is invalid or another error occurs. Compare with === 1.

What is the difference between preg_match() and preg_match_all()?

preg_match() stops at the first match. preg_match_all() finds every match in the string.

How do I escape special characters in a PHP regex?

Put a backslash before a literal special character, for example, \. for a dot. For whole strings from users, use preg_quote().

Why does my regex return false?

The pattern is probably invalid, such as an unclosed group or missing delimiter, or the engine hit a limit. Check preg_last_error_msg().

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
PHP Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum