Regular Expressions in PHP with Examples: In Practice
Regular expressions (regex) are a powerful tool for searching, replacing, and analyzing text. In PHP, they are implemented through a set of PCRE (Perl Compatible Regular Expressions) functions. It's hard to imagine form validation, log parsing, or template replacement in strings without them.
In this article, we will break down regular expressions in PHP with examples that you can immediately apply in your projects. We won't delve into theory — only practice, code, and real-world scenarios.
1. Basic Functions for Working with Regex in PHP
PHP has three key functions that cover 95% of tasks:
preg_match()— search for the first match.preg_match_all()— search for all matches.preg_replace()— replace using a pattern.preg_split()— split a string using a pattern.
All functions require three parameters: pattern, subject string, and optional flags.
Example 1: Email Validation
<?php$email = "user@example.com";$pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/";
if (preg_match($pattern, $email)) { echo "Email is valid";} else { echo "Email is invalid";}?>Let's break down the pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/
^— start of string.[a-zA-Z0-9._%+-]+— one or more allowed characters.@— literal @ character.[a-zA-Z0-9.-]+— domain name.\\.— dot (escaped).[a-zA-Z]{2,}— domain zone (minimum 2 letters).$— end of string.
Example 2: Extracting All Links from HTML
<?php$html = '<a href="https://pythonlib.ru">Site</a> and <a href="/about">About Us</a>';$pattern = '/href="([^"]+)"/';
preg_match_all($pattern, $html, $matches);
print_r($matches[1]); // Will output an array of links?>Here ([^"]+) is a capturing group that searches for everything except quotes inside the href attribute.
2. Modifiers and Their Practical Application
Modifiers change the behavior of a regular expression. They are placed after the closing slash (/).
i— case-insensitive search.m— multiline mode (^ and $ work for each line).s— dot matches newline.U— lazy mode (greedy by default).u— UTF-8 support.
Example 3: Case-Insensitive Word Search
<?php$text = "PHP is a powerful language. php is used everywhere.";$pattern = "/php/i";
preg_match_all($pattern, $text, $matches);echo count($matches[0]); // Will output 2?>Example 4: Working with Cyrillic (UTF-8)
<?php$text = "Hello, world!";$pattern = "/[a-z]+/ui"; // u — UTF-8, i — case-insensitivity
preg_match_all($pattern, $text, $matches);print_r($matches[0]); // ['Hello', 'world']?>Without the u modifier, Cyrillic will be processed incorrectly because PHP treats each byte as a separate character.
3. Replacing and Splitting Strings with Regular Expressions
The preg_replace() function allows you to replace parts of a string using a pattern. And preg_split() splits a string like explode, but with the ability to use a regex.
Example 5: Cleaning Text from HTML Tags
<?php$html = "<h1>Heading</h1><p>Text with a <b>bold</b> word</p>";$clean = preg_replace("/<[^>]+>/", "", $html);echo $clean; //