Codeskill

Learn to code, step by step

Regular Expressions in PHP: Pattern Matching and Text Parsing

Regular expressions in PHP – pattern matching and text parsing using the preg_ functions.

What are regular expressions?

Regular expressions (regex) are search patterns written as strings. PHP uses them to find, match, and replace text – validating email addresses, pulling URLs from a block of text, that sort of thing.

Basic syntax

Patterns go inside forward slashes: /pattern/. Special characters inside the pattern define what you are searching for.

Using regex in PHP

PHP has two sets of regex functions. The older POSIX ones (ereg() and friends) are deprecated. Use the PCRE functions (preg_) – they are more capable and what everyone uses now.

preg_match() – finding a match

Returns true if the pattern is found, false otherwise.

<?php
$str = "Visit OpenAI";
$pattern = "/openai/i"; // 'i' after the pattern delimiter indicates case-insensitive search
if (preg_match($pattern, $str)) {
    echo "Pattern found!";
} else {
    echo "Pattern not found.";
}
?>

preg_match_all() – finding all matches

Use this when you need every occurrence, not just the first.

<?php
$str = "The rain in SPAIN falls mainly on the plain.";
$pattern = "/ain/i";
preg_match_all($pattern, $str, $matches);
print_r($matches);
?>

preg_replace() – replacing text

Search and replace using a regex pattern.

<?php
$str = "Welcome to OpenAI!";
$pattern = "/openai/i";
$replacement = "GPT-4";
echo preg_replace($pattern, $replacement, $str);
?>

Writing regular expressions

A few building blocks to get started:

  • Literals: ordinary characters that match themselves.
  • Metacharacters: special characters like * (zero or more), + (one or more), ? (zero or one), . (any single character), and ^ (start of string).
  • Character classes: enclosed in [], match any one of several characters. [abc] matches a, b, or c.
  • Quantifiers: specify how many times a character or group must appear. a{2} matches aa.
  • Escape sequences: use \ to match special characters literally.

Practical examples

Validating an email address

<?php
$email = "test@example.com";
$pattern = "/^\S+@\S+\.\S+$/";
if (preg_match($pattern, $email)) {
    echo "Valid email address!";
} else {
    echo "Invalid email address!";
}
?>

This is a basic check. For production, use PHP’s built-in filter_var() with FILTER_VALIDATE_EMAIL instead.

Extracting URLs from text

<?php
$text = "Check out https://www.openai.com and http://example.com";
$pattern = "/\bhttps?:\/\/\S+/i";
preg_match_all($pattern, $text, $urls);
print_r($urls[0]);
?>

Advanced patterns

Once the basics click, you can use grouping, lookaheads, and other constructs for more complex matching. Build up gradually.

Tips

  • Start simple: get a basic pattern working, then add complexity.
  • Use online tools: regex101.com is handy for testing and debugging.
  • Readability matters: complex regex is hard to read. Comment it, or break it into smaller parts.

Regex looks intimidating at first. Start with simple patterns and work up – it becomes a useful tool once you have used it a few times.

PreviousError Handling in PHP: Graceful Recovery