|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #81469 preg_replace(): add support for named capture groups
Submitted: 2021-09-23 13:01 UTC Modified: 2021-09-24 05:29 UTC
From: wim at squeezely dot tech Assigned:
Status: Closed Package: PCRE related
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
Block user comment
Status: Assign to:
Bug Type:
From: wim at squeezely dot tech
New email:
PHP Version: OS:


 [2021-09-23 13:01 UTC] wim at squeezely dot tech
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}"


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2021-09-23 15:57 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.
 [2021-09-24 05:29 UTC] wim at squeezely dot tech
-Status: Open +Status: Closed
 [2021-09-24 05:29 UTC] wim at squeezely dot tech
Okay, I'll use preg_replace_callback instead. I just thought it would be nice if preg_replace() would support the capabilities of regex completely. But it makes sense to spend time on other things.

PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Sat Oct 23 20:03:34 2021 UTC