# Creating Custom PHP Replacements with preg_replace_callback

By Dinesh Uprety
Published: 2025-11-09
Updated: 2025-11-10
Canonical: https://laranepal.com/blog/creating-custom-php-replacements-with-preg-replace-callback

# Creating a Custom Replacement Function in PHP

Sometimes, PHP’s default string replacement functions just aren’t enough. For instance, you might want to replace specific patterns — like acronyms — with their full forms dynamically. That’s where [`preg_replace_callback()`](https://www.php.net/manual/en/function.preg-replace-callback.php) comes in.

This powerful function lets you define a **custom callback** that decides how each match should be replaced.

---

## How `preg_replace_callback()` Works

**Syntax:**

```php
<?php
    preg_replace_callback(
        string|array $pattern,
        callable $callback,
        string|array $subject,
        int $limit = -1,
        int &$count = null,
        int $flags = 0
    ): string|array|null
?>
```

- **$pattern** – the regex pattern to search for
- **$callback** – the function to handle each match
- **$subject** – the input string
- **$limit** _(optional)_ – max replacements (-1 for all)
- **$count** _(optional)_ – stores number of replacements made

---

## Example: Expanding Acronyms Automatically

Suppose you want to replace acronyms like `IRS` or `PDF` with their full forms. Here’s how:

```php
<?php
function acronym($matches) {
    $acronyms = array(
        'WWW' => 'World Wide Web',
        'IRS' => 'Internal Revenue Service',
        'PDF' => 'Portable Document Format'
    );

    return isset($acronyms[$matches[1]])
        ? $acronyms[$matches[1]] . " ({$matches[1]})"
        : $matches[1];
}

$text = "The <acronym>IRS</acronym> offers tax forms in <acronym>PDF</acronym> format on the <acronym>WWW</acronym>.";

$newtext = preg_replace_callback(
    "/<acronym>(.*)<\/acronym>/U",
    'acronym',
    $text
);

echo $newtext;
?>
```

**Output:**

```
The Internal Revenue Service (IRS) offers tax forms in Portable Document Format (PDF) on the World Wide Web (WWW).
```

---

## Using Anonymous Functions (Closures)

With PHP 7.0 and later, you can simplify the callback using an **anonymous function**:

```php
<?php

$text = "The <acronym>IRS</acronym> offers tax forms in <acronym>PDF</acronym> format on the <acronym>WWW</acronym>.";

$newtext = preg_replace_callback(
    "/<acronym>(.*)<\/acronym>/U",
    function($matches) {
        $acronyms = [
            'WWW' => 'World Wide Web',
            'IRS' => 'Internal Revenue Service',
            'PDF' => 'Portable Document Format'
        ];
        return $acronyms[$matches[1]] ?? $matches[1];
    },
    $text
);
echo $newtext;
?>
```

---

## Bonus: `preg_replace_callback_array()`

If you need to perform **multiple pattern-callback replacements** in one go, use [`preg_replace_callback_array()`](https://www.php.net/manual/en/function.preg-replace-callback-array.php) — introduced in PHP 7.0. It lets you provide an array of pattern-callback pairs, making complex replacements cleaner and faster.

---

## Final Thoughts

`preg_replace_callback()` is ideal when you need **dynamic, logic-based replacements** in PHP. Whether it’s expanding acronyms, formatting text, or processing templates, this function gives you full control over how patterns are handled.

---
