PHP Regular Expressions

PHP regular expressions allow you to search, match, and replace patterns in strings. PHP supports two types of regular expressions:

  1. POSIX-style (deprecated)

  2. Perl-Compatible Regular Expressions (PCRE) – Most commonly used and powerful.


Basic PCRE Functions in PHP

Function Description
preg_match() Searches for a pattern in a string (returns 1 if match is found, 0 otherwise).
preg_match_all() Searches for all matches of a pattern in a string.
preg_replace() Replaces matches of a pattern in a string.
preg_split() Splits a string by a pattern.
preg_grep() Returns array elements that match a pattern.

Syntax Basics

PCRE patterns in PHP are enclosed in delimiters, usually slashes (/pattern/).

Example:

preg_match("/abc/", "abcdef"); // Returns 1

Common Patterns

Pattern Matches
. Any single character except newline
^ Start of string
$ End of string
\d Any digit (same as [0-9])
\w Any word character (letters, digits, underscore)
\s Any whitespace character
* 0 or more of the preceding element
+ 1 or more of the preceding element
? 0 or 1 of the preceding element
{n} Exactly n times
{n,} n or more times
{n,m} Between n and m times
[...] Any one character in the set
[^...] Any one character not in the set
` `

Example: Validate Email

$email = "test@example.com"; if (preg_match("/^[\w.-]+@[\w.-]+\.[a-z]{2,6}$/i", $email)) { echo "Valid email."; } else { echo "Invalid email."; }