preg_replace_callback
preg_replace_callback(string|array $pattern, callable $callback, string|array $subject, int $limit = -1, int &$count = null): string|array|null
Finds every match of a regular expression and calls a callback to compute the replacement text for each.
C C23
#include <stdio.h>
#include <regex.h>
#include <string.h>
// the "callback": look up a variable by name (NULL when unknown)
static const char *lookup(const char *key) {
if (strcmp(key, "name") == 0) return "Alice";
if (strcmp(key, "role") == 0) return "admin";
return NULL;
}
int main(void) {
const char *text = "user={{name}} role={{role}} guest={{guest}}";
regex_t re;
regcomp(&re, "\\{\\{([a-z]+)\\}\\}", REG_EXTENDED); // escaped braces (quantifier chars in ERE)
regmatch_t m[2];
char out[256] = {0};
const char *p = text;
while (regexec(&re, p, 2, m, 0) == 0) {
strncat(out, p, m[0].rm_so); // text before the match
char key[64] = {0};
memcpy(key, p + m[1].rm_so, m[1].rm_eo - m[1].rm_so);
char repl[80];
const char *v = lookup(key);
if (v != NULL) snprintf(repl, sizeof(repl), "%s", v);
else snprintf(repl, sizeof(repl), "???%s???", key);
strcat(out, repl);
p += m[0].rm_eo;
}
strcat(out, p); // trailing text
printf("%s\n", out);
regfree(&re);
return 0;
}
user=Alice role=admin guest=???guest???
C++ C++26
#include <iostream>
#include <regex>
#include <string>
#include <unordered_map>
int main() {
std::unordered_map<std::string, std::string> vars{{"name", "Alice"}, {"role", "admin"}};
std::string text = "user={{name}} role={{role}} guest={{guest}}";
std::regex re(R"(\{\{([a-z]+)\}\})"); // raw string + escaped braces
// regex_search loop: prefix() is the text before each match, suffix() the rest
std::string result;
std::string s = text;
std::smatch m;
while (std::regex_search(s, m, re)) {
result += m.prefix();
std::string key = m[1];
auto it = vars.find(key);
result += it != vars.end() ? it->second : "???" + key + "???"; // the "callback" body
s = m.suffix();
}
result += s;
std::cout << result << "\n";
return 0;
}
user=Alice role=admin guest=???guest???
C# v11.0.100
using System.Collections.Generic;
using System.Text.RegularExpressions;
var vars = new Dictionary<string, string> { ["name"] = "Alice", ["role"] = "admin" };
var text = "user={{name}} role={{role}} guest={{guest}}";
// the MatchEvaluator delegate is C#'s callback: receives the Match, returns the replacement
Console.WriteLine(Regex.Replace(text, @"\{\{([a-z]+)\}\}", m =>
{
var key = m.Groups[1].Value;
return vars.TryGetValue(key, out var v) ? v : $"???{key}???";
}));
user=Alice role=admin guest=???guest???
Go v1.27.4
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\{\{([a-z]+)\}\}`)
text := "user={{name}} role={{role}} guest={{guest}}"
vars := map[string]string{"name": "Alice", "role": "admin"}
// ReplaceAllStringFunc receives the full match only; re-match to read the capture group
fmt.Println(re.ReplaceAllStringFunc(text, func(s string) string {
m := re.FindStringSubmatch(s)
if v, ok := vars[m[1]]; ok {
return v
}
return "???" + m[1] + "???"
}))
}
user=Alice role=admin guest=???guest???
Java v27.0.1
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Map<String, String> vars = Map.of("name", "Alice", "role", "admin");
Pattern pattern = Pattern.compile("\\{\\{([a-z]+)\\}\\}");
Matcher matcher = pattern.matcher("user={{name}} role={{role}} guest={{guest}}");
// appendReplacement runs the callback per match; quoteReplacement keeps ??? and $ literal
StringBuilder result = new StringBuilder();
while (matcher.find()) {
String key = matcher.group(1);
String replacement = vars.getOrDefault(key, "???" + key + "???");
matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
}
matcher.appendTail(result);
System.out.println(result);
}
}
user=Alice role=admin guest=???guest???
JavaScript v26.13.1
const vars = { name: "Alice", role: "admin" };
const text = "user={{name}} role={{role}} guest={{guest}}";
// replace passes each capture group to the callback; /g for all matches
console.log(
text.replace(/\{\{([a-z]+)\}\}/g, (_all, key) => vars[key] ?? `???${key}???`)
);
user=Alice role=admin guest=???guest???
PHP v8.6.0
$vars = ['name' => 'Alice', 'role' => 'admin'];
// the callback receives the match array and returns the replacement text
echo preg_replace_callback('/\{\{([a-z]+)\}\}/', function ($m) use ($vars) {
return $vars[$m[1]] ?? "???{$m[1]}???";
}, 'user={{name}} role={{role}} guest={{guest}}'), "\n";
user=Alice role=admin guest=???guest???
Python v3.15.2
import re
vars = {"name": "Alice", "role": "admin"}
text = "user={{name}} role={{role}} guest={{guest}}"
# re.sub accepts a callable: receives the match, returns the replacement
print(re.sub(r"\{\{([a-z]+)\}\}", lambda m: vars.get(m.group(1), f"???{m.group(1)}???"), text))
user=Alice role=admin guest=???guest???
Rust v1.99.1
use regex::Regex; // regex crate
use std::collections::HashMap;
fn main() {
let re = Regex::new(r"\{\{([a-z]+)\}\}").unwrap();
let text = "user={{name}} role={{role}} guest={{guest}}";
let mut vars = HashMap::new();
vars.insert("name", "Alice");
vars.insert("role", "admin");
// replace_all runs the closure per match with the Captures in hand
let result = re.replace_all(text, |caps: ®ex::Captures| {
let key = &caps[1];
match vars.get(key) {
Some(v) => v.to_string(),
None => format!("???{key}???"),
}
});
println!("{}", result);
}
user=Alice role=admin guest=???guest???
TypeScript v26.13.1
// replace passes each capture group to the callback; /g for all matches
const vars: Record<string, string> = { name: "Alice", role: "admin" };
const text: string = "user={{name}} role={{role}} guest={{guest}}";
console.log(
text.replace(/\{\{([a-z]+)\}\}/g, (_all, key: string) => vars[key] ?? `???${key}???`)
);
user=Alice role=admin guest=???guest???
Language differences
C: POSIX <regex.h> has no replace API — loop regexec and stitch "prefix + callback replacement + suffix" manually; { is a quantifier metachar in ERE, so the pattern needs \{\{.
C++: std::regex_replace takes a format string only ($1 refs) — callback logic needs a regex_search loop with prefix()/suffix() stitching.
C#: the MatchEvaluator delegate (lambda) in Regex.Replace is the callback, signature Match -> string.
Go: the ReplaceAllStringFunc callback receives the full match only; re-run FindStringSubmatch inside to read capture groups (or use Expand/ExpandString for index-based expansion).
Java: no functional replace API — the idiom is a find() loop with appendReplacement (callback logic in the loop body), and the replacement must pass through Matcher.quoteReplacement so $/\ are not parsed as group refs.
JavaScript: str.replace(re, fn) natively supports callbacks (/g for all matches); the callback receives the full match and each capture group in order.
PHP: unlike preg_replace, the replacement is not a fixed string or group reference — it is computed per match (the standard tool for template rendering, case transforms, link rewriting); the callback gets $m[0] = full match and $m[1] = first group; outer variables come in via closure use.
Python: re.sub accepts a callable invoked per match — far more flexible than \1 string templates.
Rust: the regex crate's replace_all takes a closure &Captures -> String with type-safe group access.
TypeScript: same as JS, with type annotations on the callback parameters.