Peter Cos
Peter Cos

Reputation: 428

Replace a given substring before the digits

In a string like /p20 (can be any number) i want to replace the /p into /pag- but keep the number /pag-20

This is what i tried:

preg_replace('/\/p+[0-9]/', '/pag-', $string);

but the result is /pag-0

Upvotes: 1

Views: 35

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

Use a capturing group and a backreference:

$string = "/p-20";
echo preg_replace('~/p-([0-9])~', '/pag-$1', $string);
                       ^^^^^^^          ^^

Here, /p- matches a literal substring and ([0-9]) matches and captures any 1 digit into Group 1 that can be referred to with $1 backreference from the replacement pattern.

Alternatively, you may use a lookahead based solution:

preg_replace('~/p-(?=[0-9])~', '/pag-', $string);

See the PHP demo

Here, no backreference is necessary as the (?=[0-9]) positive lookahead does not consume text it matches, i.e. it does not add the text to the match value.

Upvotes: 3

Related Questions