Manic Depression
Manic Depression

Reputation: 1040

PHP preg_replace number to two parts

I need to split number with length 5 (example "11111") into two parts with space like "111 11".

What am I missing in my code?

 $zip = "11111";
 $res = preg_replace('/^\d{3}[ ]?\d{2}/', '$0 $2', $zip);
 echo $zip; // returns 11111
 echo $res; // returns 11111

Thank you very much


Thanks to all, I missed simple brackets () I need to use this to little bit difficult methods :)

Upvotes: 0

Views: 301

Answers (3)

Sharanya Dutta
Sharanya Dutta

Reputation: 4021

John Conde’s answer is great, but since your question is:

What am I missing in my code?

my answer is that you have to capture the groups with parentheses:

$zip = "11111";
$res = preg_replace('/^(\d{3})[ ]?(\d{2})/', '$1 $2', $zip);
echo $zip;
echo PHP_EOL;
echo $res;

Upvotes: 0

Marc B
Marc B

Reputation: 360902

Why use a regex for something so simple?

$zip = '11111';
$first_part = substr($zip, 0, 3);
$last_part = substr($zip, 3);

As for your regex, you're not using capture groups ((...)), so $0/$2 will never get defined.

Upvotes: 0

John Conde
John Conde

Reputation: 219934

Do you really need a regex for this? If it is always a five digit number it's easy to break it apart and reconstruct it as necessary..

echo sprintf("%s %s", substr($zip, 0, 3), substr($zip, -2));

See it in action

Upvotes: 1

Related Questions