PHP Regular Expressions

PHP Tutorial

PHP Regular Expressions (Regex)

Regular Expressions are patterns used to match, search, or replace text.

PHP supports regex in two ways:

  1. preg_ functions → recommended (Perl-compatible)

  2. ereg_ functions → deprecated (not used today)

We use preg_ functions for all modern PHP regex operations.


 PHP Regex Functions (preg_)

FunctionDescription
preg_match()Finds first match
preg_match_all()Finds all matches
preg_replace()Search & replace
preg_split()Split string by regex pattern

 1. preg_match()

Checks if the pattern exists in the string.

Example


 

/php/i

  • php → text to find

  • i → case-insensitive


 2. preg_match_all()

Finds all matches in the string.

Example


 

Output:

Array ( [0] => Array ( [0] => 10 [1] => 20 [2] => 30 ) )

 3. preg_replace()

Searches for a pattern and replaces it.

Example


 

Output:

My dog is cute.

 4. preg_split()

Splits a string using a regex.

Example: split by spaces


 


 Regex Syntax (Common Patterns)

PatternMeaning
.any character
\ddigits (0–9)
\Dnon-digits
\wword characters (a-z, A-Z, 0-9, _)
\Wnon-word characters
\swhitespace
\Snon-whitespace
^start of string
$end of string
[]a set of characters
+one or more
*zero or more
?zero or one
{n}exactly n times
{n,}n or more times
{n,m}between n and m times

 Useful Real-World Examples


 Validate Email


 


 Validate Mobile Number (10 digits)


 


 Check Username (letters, numbers, underscore)


 


 Extract All Words Starting With Capital Letter


 


Replace Multiple Spaces with Single Space


 


 Summary

FunctionPurpose
preg_match()Find first match
preg_match_all()Find all matches
preg_replace()Replace text using regex
preg_split()Split string

Regex helps with validation, searching, string cleaning, data extraction, etc.


If you want, I can also provide:

  •  Regex Cheat Sheet PDF
  •  Real-world form validation examples
  •  PHP Regex practice problems

You may also like...