0
0
PHPprogramming~5 mins

Preg_match for pattern matching in PHP

Choose your learning style9 modes available
Introduction

Preg_match helps you check if a text matches a pattern. It finds if a word or format is inside a string.

Checking if an email address is valid.
Finding if a phone number is in the right format.
Searching for a specific word in a sentence.
Validating user input like passwords or usernames.
Syntax
PHP
<?php
$pattern = '/pattern/';
$text = 'some text';
if (preg_match($pattern, $text)) {
    // code if pattern found
} else {
    // code if pattern not found
}
?>

The pattern is written between slashes /pattern/.

Preg_match returns 1 if it finds the pattern, 0 if not.

Examples
This checks if the word 'cat' is in the text.
PHP
<?php
$pattern = '/cat/';
$text = 'I have a cat.';
if (preg_match($pattern, $text)) {
    echo 'Found cat!';
} else {
    echo 'No cat here.';
}
?>
Empty text means no match found.
PHP
<?php
$pattern = '/dog/';
$text = '';
if (preg_match($pattern, $text)) {
    echo 'Found dog!';
} else {
    echo 'No dog here.';
}
?>
This checks if the text starts with 'hello'.
PHP
<?php
$pattern = '/^hello/';
$text = 'hello world';
if (preg_match($pattern, $text)) {
    echo 'Text starts with hello';
} else {
    echo 'Text does not start with hello';
}
?>
Sample Program

This program checks two texts to see if they contain any numbers using preg_match.

PHP
<?php
// Pattern to check if text contains a number
$pattern = '/\d+/';
$text_before = 'My phone number is 12345.';
$text_after = 'No numbers here.';

// Check first text
if (preg_match($pattern, $text_before)) {
    echo "Before: Number found in text.\n";
} else {
    echo "Before: No number found in text.\n";
}

// Check second text
if (preg_match($pattern, $text_after)) {
    echo "After: Number found in text.\n";
} else {
    echo "After: No number found in text.\n";
}
?>
OutputSuccess
Important Notes

Time complexity is usually fast, depends on pattern complexity.

Space complexity is low, just stores match info.

Common mistake: forgetting to escape special characters in pattern.

Use preg_match when you want to check if a pattern exists once. Use preg_match_all to find all matches.

Summary

Preg_match checks if a pattern exists in a string.

It returns 1 if found, 0 if not.

Patterns are written between slashes, like /pattern/.