3

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 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, the 2nd one works. I tried the first one but there I get PHP Notice: Undefined variable: 1
1

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.

3 Comments

@AvinashRaj: Yes, I did check that, but after I wonder why you didn't put up such answer.
Ahh .. very good, thank you. That explains the mistake I made earlier :) With the single quoted string it's working.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.