Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Regular Expressions Tutorial

Introduction

Regular expressions (regex) are sequences of characters that define a search pattern. They are used for string matching and manipulation. In PHP, regular expressions can be used for tasks such as validating input, searching and replacing text, and parsing strings.

Basic Syntax

A regular expression is typically enclosed between two forward slashes. Here’s an example:

/pattern/

The pattern can include literal characters, metacharacters, and quantifiers.

Literal Characters

Literal characters match themselves exactly. For example, the regex /cat/ will match the string "cat" in "I have a cat."

Metacharacters

Metacharacters have special meanings. Some common metacharacters are:

  • . - Matches any single character except newline
  • ^ - Matches the start of the string
  • $ - Matches the end of the string
  • [] - Matches any one of the enclosed characters
  • \ - Escapes a metacharacter

Quantifiers

Quantifiers specify the number of times a pattern should match:

  • ? - Matches 0 or 1 time
  • * - Matches 0 or more times
  • + - Matches 1 or more times
  • {n} - Matches exactly n times
  • {n,} - Matches n or more times
  • {n,m} - Matches between n and m times

Examples in PHP

Here are some examples of using regular expressions in PHP:

1. Simple Matching

We can use the preg_match() function to check if a pattern matches a string:


<?php
$pattern = "/cat/";
$string = "I have a cat.";
if (preg_match($pattern, $string)) {
    echo "Match found!";
} else {
    echo "No match.";
}
?>
                
Output: Match found!

2. Replacing Text

The preg_replace() function is used to perform a search and replace:


<?php
$pattern = "/cat/";
$replacement = "dog";
$string = "I have a cat.";
$new_string = preg_replace($pattern, $replacement, $string);
echo $new_string;
?>
                
Output: I have a dog.

3. Extracting Data

We can use the preg_match_all() function to find all matches in a string:


<?php
$pattern = "/\d+/";
$string = "There are 3 apples and 5 oranges.";
preg_match_all($pattern, $string, $matches);
print_r($matches);
?>
                
Output: Array ( [0] => Array ( [0] => 3 [1] => 5 ) )

Conclusion

Regular expressions are powerful tools for working with strings in PHP. By understanding the basic syntax, metacharacters, and quantifiers, you can perform complex string manipulations with ease.