Page 1 of 1
regex problem - adding dashes to long number?
Posted: Mon Apr 11, 2005 1:46 pm
by kirilisa
Hi,
I'm trying to format some $_POST info a certain way. The thing I get from $_POST is a 33 digit number, e.g.
$billing_code = 333333333333333333333333333333333.
I need to add dashes to the above number so that it looks like this:
$formatted_billing_code = 333-33333-3333-333333-333333-3333-33333
Can anyone tell me a quick way to do this? I was messing around with ereg_replace but I couldn't make it work.
Thanks!
Elise
Posted: Mon Apr 11, 2005 1:56 pm
by Bennettman
Well, you could always go...
Code: Select all
<?php
$i = 333333333333333333333333333333333;
$code =
substr($i,0,3).'-'.
substr($i,3,5).'-'.
substr($i,8,4).'-'.
substr($i,12,6).'-'.
substr($i,18,6).'-'.
substr($i,24,4).'-'.
substr($i,28,5);
?>
Messy, but hey.
Posted: Mon Apr 11, 2005 2:28 pm
by Chris Corbyn
Bennettman wrote:Messy, but hey.
It's a messy pattern in the first place lol (even a regex would look messy

).
If you don't need anything too strict then bennetman's is the best option.
Is the number always grouped in the same number of blocks?

Posted: Mon Apr 11, 2005 2:30 pm
by kirilisa
Yeah it always is the same number of blocks.
I'm using bennetman's suggestion right now (thank you!).
It doesn't matter to me much, I was just wondering if there were some neato way of doing it

Posted: Mon Apr 11, 2005 2:35 pm
by Chris Corbyn
Code: Select all
$formatted = preg_replace('/^\d{3}\d{5}\d{4}\d{6}\d{6}\d{4}\d{5}$/', "$1-$2-$3-$4-$5-$6-$7", $number);
You *could* even use a loop to generate that $1-$2-$3-... thing
Still think bennetman's way is good enough mind you

Posted: Mon Apr 11, 2005 2:38 pm
by Bennettman
See, told you mine was messy. ^_-
Anyway, wouldn't that be:
Code: Select all
$formatted = preg_replace("/^\d{3}\d{5}\d{4}\d{6}\d{6}\d{4}\d{5}$/", "$1-$2-$3-$4-$5-$6-$7", $code);
with the ^ moved past the first /, and the escape slashes for \d?
Edit: XD we've both been fixing up mistakes XD
Posted: Mon Apr 11, 2005 2:40 pm
by Chris Corbyn
I had edited my post before you sent your lol.
It was *full* of mistakes. $string input was missing and preg_ reuires quotes on the pattern LOL. DOH.
EDIT | DOH - i see you editted your post while I was typing this one too lol.