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?
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:
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
.