Regular Expressions in PHP: From Theory to Practice
\n\nRegular 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\n1. Basics of Regular Expression Syntax in PHP
\n\nAny regular expression in PHP is enclosed in delimiters (usually slashes /). After the closing delimiter, you can specify modifiers — flags that change the search behavior.
$pattern = '/pattern/modifiers';\n\nBasic 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
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
2. The preg_match() Function: Finding Matches
\n\npreg_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.
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\nExample 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\nNote: the u modifier is mandatory if the string contains Cyrillic or Unicode special characters.
3. The preg_replace() Function: Pattern-Based Replacement
\n\npreg_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.
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\nExample 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?><