|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2021-09-23 13:01 UTC] wim at squeezely dot tech
Description:
------------
Would it be possible to add support for named capture groups to preg_replace()?
php > var_dump(preg_replace('/([a-z]+)$/', 'ice-cream-with-${1}', 'I-like-chocolate-sprinkles'));
string(41) "I-like-chocolate-ice-cream-with-sprinkles"
Add support for:
var_dump(preg_replace('/(?<namedGroup>[a-z]+)$/', 'ice-cream-with-${namedGroup}', 'I-like-chocolate-sprinkles'));
Test script:
---------------
php > var_dump(preg_replace('/(?<namedGroup>[a-z]+)$/', 'ice-cream-with-${namedGroup}', 'I-like-chocolate-sprinkles'));
Expected result:
----------------
string(41) "I-like-chocolate-ice-cream-with-sprinkles"
Actual result:
--------------
string(45) "I-like-chocolate-ice-cream-with-${namedGroup}"
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Oct 25 16:00:02 2025 UTC |
TBH I don't think this is worthwhile anymore at this point. With preg_replace_callback you can do: preg_replace_callback('/(?<namedGroup>[a-z]+)$/', fn($m) => "ice-cream-with-$m[namedGroup]", 'I-like-chocolate-sprinkles')); Which is not much worse than dedicated syntax, and gives you the full generality of PHP without any questions about edge-case behavior.