Regular Expressions in PHP with Examples: A Complete Guide for Beginners

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: What Are They and Why Are They Needed?



Regular expressions (regex) are a powerful tool for searching, replacing, and validating strings based on patterns. In PHP, they are implemented through a set of functions that allow developers to work flexibly with text data. For beginners, this topic may seem complex, but in practice it significantly simplifies form processing, email validation, URL parsing, and many other tasks.



In this article, we will cover the basic syntax of regular expressions in PHP, review the main functions, and provide clear examples for each of them.



1. Basics of Regular Expression Syntax



A regular expression in PHP is a string enclosed in delimiters (most often a forward slash /). Inside this string are special characters (metacharacters) and ordinary characters.



Basic Metacharacters



  • . — any character except a newline.
  • ^ — start of string.
  • $ — end of string.
  • * — zero or more repetitions of the preceding character.
  • + — one or more repetitions.
  • ? — zero or one repetition.
  • \\d — any digit (equivalent to [0-9]).
  • \\w — any letter, digit, or underscore.
  • \\s — any whitespace character.
  • [] — character class (e.g., [a-z] — all lowercase Latin letters).
  • () — grouping.


Example of a Simple Pattern



Suppose we want to check if a string contains the word "php". The simplest pattern would look like this:



/php/


This pattern will find the substring "php" anywhere in the string (for example, it will not find "PHP" because case matters). To make the search case-insensitive, the i modifier is used:



/php/i


Now the pattern will match "PHP", "Php", and "php".



2. Main Functions for Working with Regular Expressions in PHP



PHP provides several key functions. Let's look at the three most popular ones: preg_match, preg_replace, and preg_split.



2.1. preg_match — Checking for a Match



The preg_match function checks whether a string matches a pattern. It returns 1 if a match is found, and 0 otherwise. You can also pass a third argument — an array that will be filled with all found matches.



Example: 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!";}?>


Pattern explanation:

  • ^ — start of string.
  • [a-zA-Z0-9._-]+ — one or more characters: Latin letters, digits, period, underscore, or hyphen.
  • @ — the mandatory "at" symbol.
  • [a-zA-Z0-9.-]+ — domain name.
  • \\. — escaped period.
  • [a-zA-Z]{2,} — domain zone (at least 2 letters).
  • $ — end of string.


2.2. preg_replace — Pattern-Based Replacement



The preg_replace function searches for matches to a pattern and replaces them with a specified string. This is especially useful for data cleaning or text formatting.



Example: Removing all digits from a string



<?php$text = "My number: 123-456-7890";$pattern = "/\\d+/";$replacement = "[DIGITS]";

$result = preg_replace($pattern, $replacement, $text);echo $result; // Outputs: "My number: [DIGITS]-[DIGITS]-[DIGITS]"?>

Blogs

Book Recommendations