preg_replace_callback_array

preg_replace_callback_array(array $pattern_callback_map, string|array $subject, int $limit = -1, int &$count = null): string|array|null

Runs a regex substitution with one callback per pattern (PHP 7+), handling many token kinds in a single call instead of stacked preg_replace_callback calls.

C C23

C23
#include <stdio.h>
#include <regex.h>
#include <string.h>

// hand-rolled multi-pattern replace: each pattern gets its own transform,
// applied in order (the preg_replace_callback_array semantics)
static void wrap_passes(const char *in, char *out) {
    const char *patterns[] = {"[0-9]+", "[a-z]+"};
    const char *open[] = {"[", "<"};
    const char *close[] = {"]", ">"};
    char buf[128];
    strncpy(buf, in, sizeof(buf) - 1);
    buf[sizeof(buf) - 1] = '\0';

    for (int p = 0; p < 2; p++) {
        regex_t re;
        regcomp(&re, patterns[p], REG_EXTENDED);
        regmatch_t m;
        const char *src = buf;
        char next[128];
        size_t w = 0;
        while (regexec(&re, src, 1, &m, 0) == 0) {
            for (int i = 0; i < m.rm_so; i++) next[w++] = src[i];
            next[w++] = open[p][0];
            for (int i = m.rm_so; i < m.rm_eo; i++) next[w++] = src[i];
            next[w++] = close[p][0];
            src += m.rm_eo; // advance past this match
        }
        strcpy(next + w, src);
        regfree(&re);
        strncpy(buf, next, sizeof(buf) - 1);
    }
    strcpy(out, buf);
}

int main(void) {
    char out[128];
    wrap_passes("abc 123", out);
    printf("%s\n", out);
    return 0;
}
Output
<abc> [123]

C++ C++26

C++26
#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string s = "abc 123";
    // no multi-pattern callback API: run one pass per pattern ($& = whole match)
    s = std::regex_replace(s, std::regex("[0-9]+"), "[$&]");
    s = std::regex_replace(s, std::regex("[a-z]+"), "<$&>");
    std::cout << s << "\n";
    return 0;
}
Output
<abc> [123]

C# v11.0.100

v11.0.100
using System.Text.RegularExpressions;

var s = "abc 123";
// MatchEvaluator per pattern: chain one Regex.Replace per pattern
s = Regex.Replace(s, @"\d+", m => $"[{m.Value}]");
s = Regex.Replace(s, @"[a-z]+", m => $"<{m.Value}>");
Console.WriteLine(s);
Output
<abc> [123]

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

func main() {
	// one func per pattern: Go applies callbacks via ReplaceAllStringFunc per regexp
	digits := regexp.MustCompile(`[0-9]+`)
	letters := regexp.MustCompile(`[a-z]+`)
	s := "abc 123"
	s = digits.ReplaceAllStringFunc(s, func(m string) string {
		return "[" + m + "]"
	})
	s = letters.ReplaceAllStringFunc(s, func(m string) string {
		return "<" + m + ">"
	})
	fmt.Println(s)

	// capture-group access: re-run FindStringSubmatch inside the callback
	user := regexp.MustCompile(`user=(\w+)`)
	score := regexp.MustCompile(`score=(\d+)`)
	text := "user=alice score=42"
	text = user.ReplaceAllStringFunc(text, func(m string) string {
		return "USER:" + strings.ToUpper(user.FindStringSubmatch(m)[1])
	})
	text = score.ReplaceAllStringFunc(text, func(m string) string {
		n, _ := strconv.Atoi(score.FindStringSubmatch(m)[1])
		return "SCORE:" + strconv.Itoa(n*2)
	})
	fmt.Println(text)
}
Output
<abc> [123]
USER:ALICE SCORE:84

Java v27.0.1

v27.0.1
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String s = "abc 123";
        // Matcher.replaceAll(Function<MatchResult,String>) (Java 9+): one callback
        // per pattern, chained in order (String.replaceAll only takes plain strings)
        s = Pattern.compile("[0-9]+").matcher(s).replaceAll(m -> "[" + m.group() + "]");
        s = Pattern.compile("[a-z]+").matcher(s).replaceAll(m -> "<" + m.group() + ">");
        System.out.println(s);

        // capture groups are available inside the lambda
        String text = "user=alice score=42";
        text = Pattern.compile("user=(\\w+)").matcher(text)
                .replaceAll(m -> "USER:" + m.group(1).toUpperCase());
        text = Pattern.compile("score=(\\d+)").matcher(text)
                .replaceAll(m -> "SCORE:" + (Integer.parseInt(m.group(1)) * 2));
        System.out.println(text);
    }
}
Output
<abc> [123]
USER:ALICE SCORE:84

JavaScript v26.13.1

v26.13.1
// no multi-pattern callback API: chain one replace(callback) per pattern
let s = "abc 123";
s = s.replace(/\d+/g, (m) => `[${m}]`);
s = s.replace(/[a-z]+/g, (m) => `<${m}>`);
console.log(s);
Output
<abc> [123]

PHP v8.6.0

v8.6.0
// one callback per pattern, applied in array order
$text = 'user=alice score=42';
echo preg_replace_callback_array([
    '/user=(\w+)/' => function ($m) { return 'USER:' . strtoupper($m[1]); },
    '/score=(\d+)/' => function ($m) { return 'SCORE:' . ((int) $m[1] * 2); },
], $text), "\n";

// $count reports total replacements across all patterns
$count = 0;
echo preg_replace_callback_array([
    '/\d+/' => function ($m) { return "[{$m[0]}]"; },
    '/[a-z]+/' => function ($m) { return "<{$m[0]}>"; },
], 'abc 123', -1, $count), " ({$count} replacements)\n";
Output
USER:ALICE SCORE:84
<abc> [123] (2 replacements)

Python v3.15.2

v3.15.2
import re

# re.sub accepts a callback; chain one pass per pattern
s = "abc 123"
s = re.sub(r"\d+", lambda m: f"[{m.group(0)}]", s)
s = re.sub(r"[a-z]+", lambda m: f"<{m.group(0)}>", s)
print(s)
Output
<abc> [123]

Rust v1.99.1

v1.99.1
use regex::Regex; // regex crate

fn main() {
    // replace_all with a closure, one pass per pattern
    let digits = Regex::new(r"[0-9]+").unwrap();
    let letters = Regex::new(r"[a-z]+").unwrap();
    let s = digits.replace_all("abc 123", |c: &regex::Captures| format!("[{}]", &c[0]));
    let s = letters.replace_all(&s, |c: &regex::Captures| format!("<{}>", &c[0]));
    println!("{}", s);
}
Output
<abc> [123]

TypeScript v26.13.1

v26.13.1
// no multi-pattern callback API: chain one replace(callback) per pattern
let s: string = "abc 123";
s = s.replace(/\d+/g, (m) => `[${m}]`);
s = s.replace(/[a-z]+/g, (m) => `<${m}>`);
console.log(s);
Output
<abc> [123]

Language differences

C: fully hand-rolled — loop regexec per pattern in order and assemble replacement text by hand; there is no callback mechanism.

C++: no multi-pattern callback API — run one std::regex_replace per pattern (format specifier $& refers to the whole match, ECMAScript rules).

C#: the MatchEvaluator delegate in Regex.Replace is the callback; multiple patterns = chaining one Replace per pattern.

Go: ReplaceAllStringFunc only receives the whole match string; to use capture groups the callback must run FindStringSubmatch again (or hand-expand with FindStringSubmatchIndex + ExpandString).

Java: the lambda overload Matcher.replaceAll(Function<MatchResult,String>) (Java 9+) is the callback (String.replaceAll only accepts plain-string replacements), and group(n) reads capture groups directly inside it.

JavaScript: no counterpart — chain one replace(/…/g, callback) per pattern; a true multi-pattern single scan needs one big regex with dispatch inside the callback.

PHP: preg_replace_callback_array (PHP 7+) takes patterns as keys and callbacks as values, handling many token kinds in one call; each pattern is applied to the whole subject in array order (not a simultaneous single scan), and $count totals replacements across all patterns. It is the tidy replacement for stacked preg_replace_callback calls — when each pattern has its own logic, this beats one big regex with an if-chain inside the callback.

Python: the lambda argument of re.sub is the callback; multiple patterns = chaining one re.sub per pattern.

Rust: the regex crate's replace_all accepts a FnMut(&Captures) -> String closure; multiple patterns = chaining one replace_all per pattern.

TypeScript: same as JS.