PHP Regex MetaCharacters Tutorial 🎯

beginner
25 min

PHP Regex MetaCharacters Tutorial 🎯

Welcome to our comprehensive guide on PHP Regex MetaCharacters! This tutorial is designed to help both beginners and intermediates understand and master the powerful regular expression meta-characters in PHP. Let's dive in!

Introduction πŸ“

Regular expressions (or Regex) are a sequence of characters that form a search pattern. In PHP, they are used to search, replace, and manipulate text. Meta-characters are special characters that have a different meaning within the regular expression.

Escape Sequences πŸ’‘

Before we delve into the meta-characters, let's understand escape sequences. In PHP, a backslash () is used to escape special characters. For example:

php
echo "\n"; // prints a newline

Basic MetaCharacters πŸ’‘

. (Dot)

The dot represents any single character except for a newline.

php
$pattern = "/./"; $subject = "Hello World"; preg_match($pattern, $subject, $matches); print_r($matches); // outputs Array ( [0] => H )

^ (Caret)

The caret represents the start of a line.

php
$pattern = "/^H/"; $subject = "Hello World"; preg_match($pattern, $subject, $matches); if ($matches) { echo "Matched"; } else { echo "Not Matched"; } // Outputs: Matched

$ (Dollar)

The dollar sign represents the end of a line.

php
$pattern = "/World$/"; $subject = "Hello World"; preg_match($pattern, $subject, $matches); if ($matches) { echo "Matched"; } else { echo "Not Matched"; } // Outputs: Not Matched

[] (Brackets)

Brackets are used to define a character class.

php
$pattern = "/[AEIOU]/"; $subject = "Apple"; preg_match($pattern, $subject, $matches); if ($matches) { echo "Matched"; } else { echo "Not Matched"; } // Outputs: Matched

Quantifiers πŸ’‘

Quantifiers are used to specify the number of occurrences of a character or a pattern.

{n}

Matches exactly n occurrences.

php
$pattern = "/Hello/{3}/"; $subject = "Hello Hello Hello"; preg_match($pattern, $subject, $matches); if ($matches) { echo "Matched"; } else { echo "Not Matched"; } // Outputs: Matched

{n,}

Matches n or more occurrences.

php
$pattern = "/Hello/{2,}/"; $subject = "Hello Hello Hello"; preg_match($pattern, $subject, $matches); if ($matches) { echo "Matched"; } else { echo "Not Matched"; } // Outputs: Matched

{n,m}

Matches between n and m occurrences.

php
$pattern = "/Hello/{2,3}/"; $subject = "Hello Hello Hello Hello"; preg_match($pattern, $subject, $matches); if ($matches) { echo "Matched"; } else { echo "Not Matched"; } // Outputs: Matched

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

Which meta-character represents the end of a line?

Stay tuned for more on PHP Regex MetaCharacters! In the next part, we'll cover more advanced meta-characters. πŸŽ‰


Remember to check out CodeYourCraft for more in-depth tutorials on PHP and other programming topics! 🌟

Happy learning! πŸ“šπŸ’»