Jan Wytze
Jan Wytze

Reputation: 3497

PHP preg_replace reuse editted match in replacement

I am trying to create an URL matching pattern where the route parameters can be read.

This is what I have:

$routePattern = '/test/{id}/edit';
// Can I strip the opening and closing bracket from `$0` here?
$regexPattern = '#^' . preg_replace('#{[\w]+}#', '(?P<$0>[\w]+)', $routePattern) . '$#';
// Matching done here...

The problem is that this will result in: #^test/(?P<{id}>[\w]+)/edit$#. But I would like that the brackets get stripped from id. So I would like the following result: #^test/(?P<id>[\w]+)/edit$#.

How is this possible in a clean way? This is the non clean way I found:

$routePattern = '/test/{id}/edit';
$regexPattern = '#^' . preg_replace('#{[\w]+}#', '(?P<$0>[\w]+)', $routePattern) . '$#';
$regexPattern = str_replace(['{', '}'], '', $regexPattern);
// Matching done here...

Upvotes: 0

Views: 202

Answers (2)

Alexandra
Alexandra

Reputation: 56

I'd probably use a capture group, and backreference that:

({)(.)*(})

Should catch it. Then backreference it with $2 instead of $0

So..

$regexPattern = '#^' . preg_replace('#({)([\w]+)(})#', '(?P<$2>[\w]+)', $routePattern) . '$#';
// Matching done here...

Like that?

This is a great resource for regex'ing things: https://regexr.com/

Upvotes: 0

Matt S
Matt S

Reputation: 15364

Use a capturing subpattern by surrounding the \w+ in parenthesis:

preg_replace('#{([\w]+)}#', '(?P<$1>[\w]+)', $routePattern)

Upvotes: 1

Related Questions