Master PHP’s preg_match: Simple Regex and Email Validation

This guide explains how to use PHP’s preg_match function for basic string matching, demonstrates common regex patterns such as character ranges and quantifiers, and provides a detailed example for validating email addresses, helping developers apply regular expressions effectively in their backend code.

php Courses
php Courses
php Courses
Master PHP’s preg_match: Simple Regex and Email Validation

Regular expressions are a powerful text‑matching tool available in many programming languages. In PHP, the preg_match function lets you apply a regex pattern to a string and act on the result.

Simple string match example :

<?php
// String to test
$string = "Hello, World!";

// Check if "World" appears in the string
if (preg_match("/World/", $string, $matches)) {
    echo "Match successful!";
} else {
    echo "Match failed!";
}
?>

If the pattern "/World/" is found, the script prints “Match successful!”; otherwise it prints “Match failed!”.

Common regex patterns you can use with preg_match include:

Match letters A‑Z: /[A-Z]/ Match digits 0‑9: /[0-9]/ Match any character: /./ Match repeated characters: /a{3}/ (matches three consecutive "a" characters)

Match whole words: /\bword\b/ Email validation example demonstrates a more complex pattern:

<?php
// Email address to test
$email = "[email protected]";

// Validate email format
if (preg_match("/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[A-Za-z]{2,}$/", $email)) {
    echo "Email address is valid!";
} else {
    echo "Email address is invalid!";
}
?>

The regex checks for a typical email structure; a valid address triggers the success message, while an invalid one triggers the failure message.

Overall, using preg_match with appropriate regular expressions provides a flexible and powerful way to perform precise string matching and manipulation in PHP backend development.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

regexstring-matchingpreg_matchemail-validation
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.