PHP preg_match() Tutorial 🎯

beginner
5 min

PHP preg_match() Tutorial 🎯

Welcome to our comprehensive PHP preg_match() tutorial! In this guide, we'll delve into the world of regular expressions and learn how to use the powerful preg_match() function in your PHP projects. Let's get started!

What is preg_match()? πŸ“

preg_match() is a PHP function that allows you to search for a pattern in a given string using Regular Expressions (regex). It returns the number of successful matches or false if no match is found.

Why Use preg_match()? πŸ’‘

preg_match() is a versatile tool that helps you:

  • Validate user inputs (e.g., email, password)
  • Extract specific information from text (e.g., phone numbers, dates)
  • Perform text transformations (e.g., replace, split, count)
  • Implement complex search and replace tasks

How to Use preg_match() πŸ’‘

php
<?php $pattern = '/your_pattern/'; $subject = 'your_text'; if (preg_match($pattern, $subject)) { echo "Match found!"; } else { echo "No match found."; } ?>

πŸ“ Note: The pattern is enclosed in slashes (/.../), and the subject is the text you want to search.

Basic Regular Expressions πŸ’‘

Let's explore some basic regex elements:

  • .: Matches any character except a newline
  • ^: Matches the start of a line
  • $: Matches the end of a line
  • *: Matches zero or more occurrences of the preceding character
  • +: Matches one or more occurrences of the preceding character
  • ?: Matches zero or one occurrence of the preceding character
  • []: Matches any character within the square brackets
  • ^ (inside []): Matches any character not within the square brackets

Advanced Regular Expressions πŸ’‘

  • |: Matches either of the characters/patterns on either side
  • (): Creates a group
  • \d: Matches a digit (equivalent to [0-9])
  • \w: Matches a word character (equivalent to [a-zA-Z0-9_])
  • \s: Matches a whitespace character
  • \b: Matches a word boundary

Examples πŸ’‘

Example 1: Matching any word ending with 'world'

php
<?php $pattern = '/\b[a-z]+world\b/i'; $subject = "Hello world, Welcome to CodeYourCraft's world."; if (preg_match($pattern, $subject)) { echo "Match found!"; } else { echo "No match found."; } ?>

Example 2: Validating an email address

php
<?php $pattern = '/\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\Z/iD'; $email = "user@example.com"; if (preg_match($pattern, $email)) { echo "Valid email."; } else { echo "Invalid email."; } ?>

πŸ’‘ Pro Tip: The above email validation pattern (courtesy of RFC 5322) is quite robust but might not cover all possible email formats. It's essential to remember that email validation is a complex task and might require additional checks.

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

Which regex pattern matches email addresses that end with `.info` or `.net`?