note 129345 added to function.preg-replace
| From: | Anonymous | Date: | Fri, 22 Mar 2024 14:02:06 +0000 |
| Subject: | note 129345 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221251@lists.php.net to get a copy of this message | ||
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
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.13.131 (proxied: 84.236.79.56)
----
Manual Page -- https://php.net/manual/en/function.preg-replace.php
Edit -- https://main.php.net/note/edit/129345
Del: integrated -- https://main.php.net/note/delete/129345/integrated
Del: useless -- https://main.php.net/note/delete/129345/useless
Del: bad code -- https://main.php.net/note/delete/129345/bad+code
Del: spam -- https://main.php.net/note/delete/129345/spam
Del: non-english -- https://main.php.net/note/delete/129345/non-english
Del: in docs -- https://main.php.net/note/delete/129345/in+docs
Del: other reasons-- https://main.php.net/note/delete/129345
Reject -- https://main.php.net/note/reject/129345
Search -- https://main.php.net/manage/user-notes.php