Regular Expressions in PHP with Examples: In Practice

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Regular Expressions in PHP: From Theory to Practice

\n\n

Regular expressions (regex or regexp) are a powerful tool for searching, replacing, and validating strings based on a given pattern. In PHP, they are implemented through a set of PCRE (Perl Compatible Regular Expressions) functions and allow you to solve tasks of any complexity: from email validation to parsing HTML code. In this article, we will break down the syntax, main functions, and look at practical examples that will be useful for every PHP developer.

\n\n

1. Basics of Regular Expression Syntax in PHP

\n\n

Any regular expression in PHP is enclosed in delimiters (usually slashes /). After the closing delimiter, you can specify modifiers — flags that change the search behavior.

\n\n
$pattern = '/pattern/modifiers';
\n\n

Basic metacharacters:

\n
    \n
  • . — any single character (except newline)
  • \n
  • * — zero or more repetitions of the previous character
  • \n
  • + — one or more repetitions
  • \n
  • ? — zero or one repetition (makes the quantifier lazy)
  • \n
  • ^ — start of string
  • \n
  • $ — end of string
  • \n
  • \\d — digit (0-9)
  • \n
  • \\w — letter, digit, or underscore
  • \n
  • \\s — whitespace character
  • \n
  • [] — character class (e.g., [a-z])
  • \n
  • () — capturing group
  • \n
\n\n

Popular modifiers:

\n
    \n
  • i — case-insensitive search
  • \n
  • m — multiline mode (^ and $ work for each line)
  • \n
  • u — UTF-8 support (required for Cyrillic)
  • \n
  • s — dot also matches newline
  • \n
\n\n

2. The preg_match() Function: Finding Matches

\n\n

preg_match() is the most popular function. It checks whether a string matches a pattern and returns 1 (match found) or 0 (no match). The third parameter is an array into which the found matches are written.

\n\n

Example 1. Email Address Validation

\n
<?php\n$email = "user@example.com";\n$pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/';\n\nif (preg_match($pattern, $email)) {\n    echo "Email is valid";\n} else {\n    echo "Email is invalid";\n}\n// Output: Email is valid\n?>
\n\n

Example 2. Extracting Data from a String

\n
<?php\n$text = "My number: +7 (999) 123-45-67";\n$pattern = '/\\+7\\s*\\(\\d{3}\\)\\s*\\d{3}-\\d{2}-\\d{2}/u';\n\nif (preg_match($pattern, $text, $matches)) {\n    echo "Found number: " . $matches[0];\n}\n// Output: Found number: +7 (999) 123-45-67\n?>
\n\n

Note: the u modifier is mandatory if the string contains Cyrillic or Unicode special characters.

\n\n

3. The preg_replace() Function: Pattern-Based Replacement

\n\n

preg_replace() searches a string for all matches of a pattern and replaces them with the specified text. You can use capturing groups $1, $2, etc. to substitute parts of the original text.

\n\n

Example 3. Formatting a Phone Number

\n
<?php\n$phone = "89991234567";\n$pattern = '/(\\d{1})(\\d{3})(\\d{3})(\\d{2})(\\d{2})/';\n$replacement = '+7 ($2) $3-$4-$5';\n\n$formatted = preg_replace($pattern, $replacement, $phone);\necho $formatted; // +7 (999) 123-45-67\n?>
\n\n

Example 4. Cleaning HTML from Tags (Except Allowed Ones)

\n
<?php\n$html = "<b>Bold</b> <script>alert('xss')</script> text";\n$pattern = '/<\\s*\\/?\\s*(?!b|i|u|a\\b)[^>]*>/ui';\n\n$clean = preg_replace($pattern, '', $html);\necho $clean; // <b>Bold</b>  text\n?><                

Blogs

Book Recommendations