2

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);

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Use a negative lookahead assertion.

\{(?!id\})[a-z]+\}
  • (?!id\}) asserts the previous token { would be followed by any but not of id}.
  • If yes, then match one or more lower case letters and then }.

DEMO

Example:

This will replace all the matched substrings with {foo}.

preg_replace('~\{(?!id\})[a-z]+\}~', '{foo}', $str);

DEMO

4 Comments

When I use that regex on my function above I get: preg_replace_callback(): Delimiter must not be alphanumeric or backslash
pls use ~ as regex delimiter.
Thanks, but now I get Undefined offset: 1
I've posted my full code at the bottom of my original post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.