CKTIS / PHP
preg_replace_callback()
Build the replacement for each match by returning a string from a callback.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
preg_replace_callback(string|array $pattern, callable $callback, string|array $subject, int $limit = -1, int &$count = null, int $flags = 0): string|array|nullBuild the replacement for each match by returning a string from a callback. Index zero contains the full match and later indices contain captures. The returned text is used literally. count reports substitutions across all subjects. An invalid pattern returns null for a string subject and an empty array for a one-string array subject. A callback exception propagates.
Signature
preg_replace_callback(string|array $pattern, callable $callback, string|array $subject, int $limit = -1, int &$count = null, int $flags = 0): string|array|null
Example output
["$3 $10",2]
[null,[]]
RuntimeException
Examples
<?php
$result=preg_replace_callback("~#(\\d+)~",fn($m)=>"$".((int)$m[1]+1),"#2 #9",-1,$n);
echo json_encode([$result,$n]);
set_error_handler(fn($level)=>$level===E_WARNING); $a=preg_replace_callback("~[~",fn($m)=>"","x"); $b=preg_replace_callback("~[~",fn($m)=>"",["x"]); restore_error_handler(); echo "\n",json_encode([$a,$b]);
try {preg_replace_callback("~x~",fn($m)=>throw new RuntimeException(),"x");} catch (RuntimeException $e) { echo "\n",get_class($e); }
Result
["$3 $10",2] [null,[]] RuntimeException