Table of contents
1.
Introduction
2.
Syntax
3.
Parameters
3.1.
Pattern
3.2.
Subject
3.3.
Matches
3.4.
Flags
3.5.
Offset
4.
Return Value
5.
Examples
5.1.
Example 1: Finding a Word
5.2.
Example 2: Checking for Numbers
5.3.
Example 3: Finding Multiple Words
6.
Frequently Asked Questions
6.1.
What does preg_match return if it finds no match?
6.2.
Can preg_match look for multiple patterns at the same time?
6.3.
Why are patterns in preg_match surrounded by slashes (/)?
7.
Conclusion
Last Updated: Aug 13, 2025
Easy

PHP Preg_Match

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

PHP's preg_match function is like a treasure hunt tool for anyone working with text data. It helps you search through strings to find specific patterns – almost like playing a game of "Where's Waldo?" but with text. 

PHP Preg_Match

This article will guide you through mastering preg_match, from understanding its basic rules to applying it in your projects. We'll explore how it works, dissect its components, and provide you with examples to get you started. 

Syntax

The preg_match function in PHP looks a bit like a secret code at first glance, but it's actually pretty straightforward once you get the hang of it. Here’s the basic setup:

preg_match(pattern, subject, matches, flags, offset)

Parameters

In the world of preg_match, think of parameters as the ingredients in a recipe. Each one has a specific role that helps complete the dish, or in this case, the function's task. Let's break them down into simpler terms:

Pattern

Imagine you have a magnifying glass that can find specific words or letters in a book. This "pattern" is what you're telling the magnifying glass to look for. It's written in a special code language called "regular expressions" that preg_match understands.

Subject

This is the book you're using your magnifying glass on. It's the text or string where you want to find something. You can think of it as a sentence, a paragraph, or even a whole story.

Matches

When your magnifying glass finds something, you need a place to keep it. "Matches" is like a little box where preg_match puts what it finds. If it doesn't find anything, the box stays empty.

Flags

Sometimes, you want to use your magnifying glass in a special way. Maybe you want to start looking from the middle of the book, or you only want to find the first word "cat" and ignore the rest. "Flags" help you do that by changing how preg_match searches.

Offset

This is like telling your magnifying glass where in the book to start looking. If you don't want to start from the beginning, you can say, "Start looking from page 10." This is what "offset" does; it sets the starting point for the search.

By understanding these ingredients, you can use preg_match more effectively. It's like knowing how to mix the right spices to make your food taste better. Each parameter has a role that helps preg_match do its job just right.

simple example:

<?php
$pattern = "/cat/";
$subject = "The cat is on the mat";
if (preg_match($pattern, $subject)) {
  echo "Match found!";
} else {
  echo "Match not found.";
}
?>


In this code, we're looking for the word "cat" in the sentence "The cat is on the mat". If preg_match finds "cat", it tells us "Match found!". If not, we get "Match not found.".

Return Value

When you use preg_match, it's like playing a game where you're trying to find hidden treasures in a map. Once you've done your search, the game tells you if you've won or not. In the same way, preg_match gives back a special kind of message after it looks through your text. This message is what we call the "return value."

Here's how it works:

  • If preg_match finds what you're looking for, it's like winning the game. It gives back a number, which is usually 1, to say, "Yes, I found it!"
     
  • If preg_match doesn't find anything, it's like not finding the treasure. It gives back 0, which means, "Sorry, I didn't find what you were looking for."
     

Sometimes, the game might not work properly because of some mistake or issue. If that happens, preg_match gives back a false, which is like the game saying, "Oops, something went wrong."

To make this easier to understand, let's look at a simple example. Imagine we're looking for the word "dog" in the sentence "I love my dog." Here's how we might write that in code:

<?php
$pattern = "/dog/";
$subject = "I love my dog";
$result = preg_match($pattern, $subject);
if ($result == 1) {
  echo "Yes, found it!";
} elseif ($result == 0) {
  echo "Nope, it's not there.";
} else {
  echo "Hmm, something's not right.";
}
?>


In this example, preg_match is looking for "dog" in "I love my dog." Since "dog" is there, preg_match gives back 1, and our code says "Yes, found it!"

Understanding the return value helps you know whether your search was successful or not, just like knowing if you've won the game or need to try again.

Examples

Example 1: Finding a Word

Imagine we have a sentence: "The quick brown fox jumps over the lazy dog," and we want to find the word "fox" in it. Here's how we can do that:

<?php
$pattern = "/fox/";
$subject = "The quick brown fox jumps over the lazy dog";
if (preg_match($pattern, $subject)) {
  echo "We found 'fox' in the sentence!";
} else {
  echo "No 'fox' here.";
}
?>


In this code, preg_match is like a detective looking for the word "fox." If it finds "fox," it tells us by saying, "We found 'fox' in the sentence!"

Example 2: Checking for Numbers

Now, let's say we want to check if a string has any numbers in it. We could have a password, and we want to make sure it includes at least one number. Here's how we might do that:

<?php
$pattern = "/[0-9]/"; // This means any number from 0 to 9
$subject = "MyPassword123";
if (preg_match($pattern, $subject)) {
  echo "Your password has a number.";
} else {
  echo "Your password needs at least one number.";
}
?>


In this example, preg_match looks for any number between 0 and 9 in "MyPassword123." Since there are numbers, it says, "Your password has a number."

Example 3: Finding Multiple Words

Let's get a bit more adventurous. Suppose we want to see if a sentence has either the word "cat" or "dog" in it. We can use preg_match for this too:

<?php
$pattern = "/cat|dog/"; // The "|" means "or"
$subject = "I love my cat and my dog";
if (preg_match($pattern, $subject)) {
  echo "Found 'cat' or 'dog' in the sentence!";
} else {
  echo "Neither 'cat' nor 'dog' is in the sentence.";
}
?>


Here, preg_match is on a mission to find "cat" or "dog." It finds both, so it tells us, "Found 'cat' or 'dog' in the sentence!"

Frequently Asked Questions

What does preg_match return if it finds no match?

preg_match returns 0 when it doesn't find any match in the subject string.

Can preg_match look for multiple patterns at the same time?

Yes, preg_match can search for multiple patterns using the "or" operator, represented by a pipe symbol (|), within the pattern.

Why are patterns in preg_match surrounded by slashes (/)?

The slashes (/) are delimiters that mark the beginning and end of the pattern in preg_match. They are required to distinguish the pattern from other parts of the expression.

Conclusion

In conclusion, mastering PHP's preg_match function can significantly enhance your ability to work with strings and patterns in your coding projects. From finding specific words to validating complex text structures, preg_match offers a flexible and powerful tool for navigating and manipulating text data. By understanding its syntax, parameters, return values, and practical applications through examples, you're now better equipped to implement preg_match effectively in your own work. Remember, practice is key to getting comfortable with regular expressions and making the most of preg_match's capabilities. Happy coding!

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass