Reputation: 1317
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?
Upvotes: 3
Views: 1278
Reputation: 56829
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
.
Upvotes: 1
Reputation: 174874
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)
Upvotes: 3