Search and replace number in string with PHP preg_replace

1.2k views Asked by At

I've got this format: 00-0000 and would like to get to 0000-0000.

My code so far:

<?php
$string = '11-2222';
echo $string . "\n";
echo preg_replace('~(\d{2})[-](\d{4})~', "$1_$2", $string) . "\n";
echo preg_replace('~(\d{2})[-](\d{4})~', "$100$2", $string) . "\n";

The problem is - the 0's won't be added properly (I guess preg_replace thinks I'm talking about argument $100 and not $1)

How can I get this working?

2

There are 2 answers

3
nhahtdh On

The replacement string "$100$2" is interpreted as the content of capturing group 100, followed by the content of capturing group 2.

In order to force it to use the content of capturing group 1, you can specify it as:

echo preg_replace('~(\d{2})[-](\d{4})~', '${1}00$2', $string) . "\n";

Take note how I specify the replacement string in single-quoted string. If you specify it in double-quoted string, PHP will attempt (and fail) at expanding variable named 1.

1
Avinash Raj On

You could try the below.

echo preg_replace('~(?<=\d{2})-(?=\d{4})~', "00", $string) . "\n";

This will replace hyphen to 00. You still make it simple

or

preg_replace('~-(\d{2})~', "$1-", $string)