CakeFest 2025 Madrid: The Official CakePHP Conference

Voting

: max(zero, six)?
(Example: nine)

The Note You're Voting On

Anonymous
1 year ago
You can only use numeric backreferences in the replacement string, but not named ones:
<?php
echo preg_replace('#(\d+)#', '\1 $1 ${1}', '123');
// 123 123 123
echo preg_replace('#(?<digits>\d+)#', '\digits $digits ${digits}', '123');
// \digits $digits ${digits}
?>

To use named backreferences, you have to use preg_replace_callback:
<?php
echo preg_replace_callback('#(?<digits>\d+)#', function( $m ){
return
"$m[1] $m[digits] {$m['digits']}";
},
'123');
// 123 123 123

echo preg_replace_callback('#(?<digits>\d+)#', fn($m) => "$m[1] $m[digits] {$m['digits']}", '123');
// 123 123 123
?>

See https://bugs.php.net/bug.php?id=81469

<< Back to user notes page

To Top