Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔴 Advanced  ·  Lesson 30

Regular Expressions in PHP

In this lesson: Learn regular expressions in PHP — preg_match, preg_replace, preg_split — with email, mobile and pin-code patterns.

What is regex

A regular expression (regex) is a pattern for matching text. Instead of checking characters one by one, you describe the shape you want — "digits only", "starts with A", "an email format" — and PHP finds or changes matching text. It is powerful for validation and search-and-replace.

💡 Patterns go inside delimiters, usually slashes: /pattern/. Add i after for case-insensitive.

preg_match to test

<?php
  $pin = "1234";
  if (preg_match('/^\d{4}$/', $pin)) {
      echo "Valid 4-digit PIN";
  } else {
      echo "Invalid";
  }
?>
Valid 4-digit PIN

The pattern /^\d{4}$/ means: start, exactly 4 digits, end. preg_match returns 1 if the whole string fits — perfect for format checks.

Common pattern symbols

SymbolMeans
\dAny digit (0-9)
\wLetter, digit or underscore
.Any single character
+One or more of the previous
{4}Exactly 4 of the previous
^ and $Start and end of the string

preg_replace to change

<?php
  $text = "Call 98765 or 12345";
  // replace every run of digits with #
  echo preg_replace('/\d+/', '#', $text);
?>
Call # or #

preg_replace swaps every part that matches the pattern with new text. Here every group of digits becomes a # — handy for masking or cleaning text.

preg_match_all

To get every match, not just the first, use preg_match_all.

<?php
  $text = "Order 12 and 34 and 56";
  preg_match_all('/\d+/', $text, $matches);
  print_r($matches[0]);
?>
Array ( [0] => 12 [1] => 34 [2] => 56 )

All the numbers are collected into $matches[0]. Use this when a string can contain many things you want to pull out.

Common mistakes

  • Forgetting the delimiters. A pattern must be wrapped, e.g. /\d+/, not just \d+.
  • Missing ^ and $. Without them a partial match passes; add both to check the whole string.
  • Writing a regex for email. Use filter_var for email — it is more reliable.
  • Not escaping special characters. To match a literal dot, write \., since . means any character.

Summary

  • Regex is a pattern for matching or changing text.
  • preg_match tests if text fits a pattern (returns 1/0).
  • preg_replace swaps matching text for something new.
  • preg_match_all collects every match.
  • Wrap patterns in delimiters and use ^/$ for whole-string checks.

Next, validate input with form validation, or clean strings with PHP string functions.

Frequently Asked Questions

What is a regular expression in PHP?
A regular expression (regex) is a pattern used to match text — like checking if a string looks like an email, or finding all numbers in a sentence. PHP uses functions like preg_match and preg_replace with these patterns.
What does preg_match return?
preg_match returns 1 if the pattern is found, 0 if not, and false on error. It is used to test whether text matches a pattern, such as validating a format.
Why are patterns wrapped in slashes like /.../?
The slashes are delimiters that mark the start and end of the pattern, for example /^\d+$/. Anything after the closing slash can be a flag, like i for case-insensitive matching.
What is the difference between preg_match and preg_match_all?
preg_match stops at the first match. preg_match_all finds every match in the string and collects them all. Use the "all" version when you expect more than one result.
Should I use regex to validate an email?
For email specifically, PHP's filter_var($email, FILTER_VALIDATE_EMAIL) is more reliable than a hand-written regex. Use regex for simpler custom patterns like a PIN code or a username format.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicJSON Encode/Decode Your progress: 30 / 50 (60%) · Lesson 31 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free