Regular Expressions in PHP: A Complete Guide with Examples

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 Basics to Advanced Techniques



Regular expressions (regex) are a powerful tool for searching, replacing, and analyzing text data. In PHP, they are implemented through a set of PCRE (Perl Compatible Regular Expressions) functions. In this article, we will cover the basics of working with regular expressions, examine key functions, and provide practical examples that will help you automate string processing.



1. Basic Functions for Working with Regular Expressions in PHP



PHP provides several built-in functions for working with regular expressions. Let's look at the most popular ones.



preg_match() — Finding a Match

The preg_match() function checks whether a string matches a given pattern. It returns 1 if a match is found, and 0 otherwise.



<?php$text = "Hello, world! PHP is awesome.";$pattern = "/PHP/";

if (preg_match($pattern, $text)) { echo "The word 'PHP' was found!";} else { echo "No matches found.";}?>


If you need to get the match itself, pass a third argument — an array for the results:



<?php$text = "My email: user@example.com";$pattern = "/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}/";

if (preg_match($pattern, $text, $matches)) { echo "Found email: " . $matches[0];}?>


preg_replace() — Pattern-Based Replacement

The preg_replace() function replaces all matches of a pattern with a specified string. It is similar to str_replace(), but with support for regular expressions.



<?php$text = "Today is 15.03.2024, and tomorrow will be 16.03.2024";$pattern = "/(\\d{2})\\.(\\d{2})\\.(\\d{4})/";$replacement = "$3-$2-$1"; // Rearranging the date parts

echo preg_replace($pattern, $replacement, $text);// Outputs: Today is 2024-03-15, and tomorrow will be 2024-03-16?>


preg_split() — Splitting a String

The preg_split() function splits a string using a regular expression. This is more convenient than explode() when the delimiters can be different.



<?php$text = "apple, pear; banana: orange";$pattern = "/[,;:]/"; // Delimiters: comma, semicolon, colon$fruits = preg_split($pattern, $text);

print_r($fruits);// Array ( [0] => apple [1] => pear [2] => banana [3] => orange )?>


2. Metacharacters and Syntax of Regular Expressions



To use regular expressions effectively, you need to understand their syntax. Here are the basic metacharacters:



  • . — any character (except newline)
  • ^ — start of string
  • $ — end of string
  • * — 0 or more repetitions
  • + — 1 or more repetitions
  • ? — 0 or 1 repetition
  • \\d — digit (0-9)
  • \\w — letter, digit, or underscore
  • \\s — whitespace character
  • [abc] — any character from the set
  • (...) — capturing group


Example: Phone number validation

<?php$phone = "+7 (123) 456-78-90";$pattern = "/^\\+7\\s\\(\\d{3}\\)\\s\\d{3}-\\d{2}-\\d{2}$/";

if (preg_match($pattern, $phone)) { echo "Phone number is valid!";} else { echo "Invalid phone number format.";}?>


3. Advanced Techniques and Modifiers



Modifiers change the behavior of a regular expression. They are specified after the closing slash. Let's look at the most useful ones:



  • i — case-insensitive search
  • m — multiline mode (^ and $ work for each line)
  • s — dot includes newline character
  • u — support for UTF-8

Blogs

Book Recommendations