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!
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.
preg_match() is a versatile tool that helps you:
<?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.
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|: 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 boundaryExample 1: Matching any word ending with 'world'
<?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
$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.
Which regex pattern matches email addresses that end with `.info` or `.net`?