I want to perform a preg_replace on the string and return the named capture as well but the named capture is not showing. Below is what I have done...
string = "{hello}/{world}"
string = preg_replace("/\//", "/\/", string)
string = preg_replace("/\{[a-z]+\}/", "(?P<\1>[a-z-]+)", string)
The above is expected to become:
(?P<hello>[a-z-]+)\/(?P<world>[a-z-]+)
But I'm only getting:
(?P<>[a-z-]+)\/(?P<>[a-z-]+)
The named capture not appearing.
Edit
I'm getting:
(?P<{hello}>[a-z-]+)\/(?P<{world}>[a-z-]+)
if I change the
\1
to
\0
More Debugging
The problem is with the < > in the replacement pattern, if I remove them the \1 works fine, but how do I make regex see the < > as literals and not regex special characters. I tried preg_quote and escaping them, not working. \< is how I'm escaping them...
Capture the group before using it:
$string = preg_replace("/\{([a-z]+)\}/", "(?P<$1>[a-z-]+)", $string)
// here __^ & __^