how PHP preg_replace_callback ignore id

 

Questions


I am using the following code to match all letters except i and d.

/{([abcefghj-z]+)}/

How can I change it so that i and d can exist but not in that order (id).

Example strings:

/admin/users/{type}/{id}/edit

Only {type} would get replaced in the above example.

Example 2:

/admin/users/{type}/{id}/{supplied}/edit

In the above example both {type} and {supplied} would get matched.

Is this possible using regex?

UPDATE

The code I am using as per below post is:

$current = 'admin/users/{type}/{id}/changePassword';
$parameters = array('type' => 'administrators', 'id' => '1');

$path = preg_replace_callback('~{(?!id})[a-z]+}~', function ($m) use ($parameters) {
        return $parameters[$m[1]]; 
}, $current);

 

 

————————————————-

Answer

Here is a solution for you: you need to use a capturing group (thus I added round brackets in ([a-z]+)) to be able to get the value you need and I see you need to perform the search in a case-insensitive way (thus, I added ~i):

$current = 'admin/users/{type}/{id}/changePassword';
$parameters = array('type' => 'administrators', 'id' => '1');

$path = preg_replace_callback('~{(?!id})([a-z]+)}~i', function ($m) use ($parameters) {
//                                        ^      ^   ^
        return $parameters[$m[1]]; 
}, $current);

echo $path;

See IDEONE demo

With capturing group, $m[1] will hold “type”, and thus you will get the value from the array correctly.

php,regex

[], []