|  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
 [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-2022 The PHP Group
All rights reserved.
Last updated: Tue Aug 09 16:05:44 2022 UTC