0Pricing
PHP Academy · Lesson

Replacing Text with preg_replace

Substitute matches with replacement strings and backreferences.

Replacing Text with preg_replace is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

preg_replace() Signature

preg_replace($pattern, $replacement, $subject) returns the subject with all matches replaced. Pass an array of subjects to process multiple strings at once.

Simple Replacement

Replace all digits in a string with an asterisk.

<?php
$result = preg_replace('/\d/', '*', 'Order #12345');
echo $result; // "Order #*****"

Backreferences in Replacement

Use $1, $2... (or \1, \2) to insert captured groups into the replacement string.

<?php
$result = preg_replace('/^(\w+)\s(\w+)$/', '$2, $1', 'John Smith');
echo $result; // "Smith, John"

Named Backreferences

Named capture groups can be referenced as ${name} in the replacement.

<?php
$result = preg_replace(
    '/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})/',
    '${day}/${month}/${year}',
    '2025-06-15'
);
echo $result; // "15/06/2025"

Replacing Multiple Patterns

Pass arrays of patterns and replacements to process multiple rules at once.

<?php
$result = preg_replace(
    ['/foo/', '/bar/'],
    ['baz',   'qux'],
    'foo and bar'
);
echo $result; // "baz and qux"

Limit Parameter

The 4th parameter limits how many substitutions are made. Pass -1 for unlimited (default).

<?php
$result = preg_replace('/a/', 'X', 'banana', 2);
echo $result; // "bXnXna"

Count Parameter

Pass a 5th variable to receive the number of replacements made.

<?php
$count  = 0;
$result = preg_replace('/e/', '3', 'hello everyone', -1, $count);
echo "$count replacements"; // "3 replacements"

preg_replace_callback()

When the replacement logic is complex, use preg_replace_callback() to process each match with a closure.

<?php
$result = preg_replace_callback(
    '/\d+/',
    fn($m) => $m[0] * 2,
    'Item: 5, Qty: 3'
);
echo $result; // "Item: 10, Qty: 6"

Strip HTML Tags Example

Remove all HTML tags with a simple regex (use strip_tags() in production).

<?php
$clean = preg_replace('/<[^>]+>/', '', '<b>Hello</b> World');
echo $clean; // "Hello World"

Slugify a String

Convert a title to a URL-safe slug.

<?php
function slugify(string $s): string {
    $s = strtolower($s);
    $s = preg_replace('/[^a-z0-9]+/', '-', $s);
    return trim($s, '-');
}
echo slugify('Hello World!'); // "hello-world"

Performance Note

Keep patterns simple and avoid catastrophic backtracking. Use preg_replace_callback for complex transformations rather than stacking multiple preg_replace calls.

Difference from str_replace

str_replace is faster for plain-text replacement. Use preg_replace only when you need the power of a regex pattern.

Summary

preg_replace replaces all matches of a pattern. Use backreferences ($1) to reuse captured groups. Use preg_replace_callback when replacement logic is dynamic.

Quick Check

How do you reference the first capture group in a preg_replace replacement string?

Frequently asked questions

Is the “Replacing Text with preg_replace” lesson free?

Yes — the full text of “Replacing Text with preg_replace” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Replacing Text with preg_replace”?

Substitute matches with replacement strings and backreferences. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Replacing Text with preg_replace” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Regex Syntax Fundamentals
  2. Matching with preg_match
  3. Replacing Text with preg_replace
  4. Splitting and Practical Patterns
← Back to PHP Academy