Find and replace number in string with PHP preg_replace

I have this format: 00-0000 and would like to get to 0000-0000.

My code:

<?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 that 0 won't be added properly (I think preg_replace thinks I'm talking about the $ 100 argument and not $ 1)

How can I get this to work?

+3


source to share


2 answers


You can try the following.

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

      

This will replace the hyphen with 00

. Are you still simplifying



or

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

      

+3


source


The swap string is "$100$2"

interpreted as the content of capture group 100, followed by the content of capture group 2.

To force it to use the content of capturing group 1, you can specify it like:



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

      

Notice how I am specifying the replacement string in the single quoted string. If you specify it in a double quoted string, PHP will try (and won't) when expanding the variable named 1

.

+1


source







All Articles