简体   繁体   中英

Search and replace number in string with PHP preg_replace

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?

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM