Page 1 of 1

format string

Posted: Tue Aug 05, 2008 11:15 am
by bouncer
hi there,

i have this string "0001", and i want to format it like this "000 1" how can i do this, if it's possible ?

thanks in advance

Re: format string

Posted: Tue Aug 05, 2008 11:17 am
by chaos
Well... you could achieve that with preg_replace('/.$/', ' $1', $yourstring). But it's not clear at all whether there's a deeper principle involved than inserting a space before the last character. If there's more that your formatting needs to do, you should describe it.

Re: format string

Posted: Tue Aug 05, 2008 11:32 am
by bouncer
chaos wrote:Well... you could achieve that with preg_replace('/.$/', ' $1', $yourstring). But it's not clear at all whether there's a deeper principle involved than inserting a space before the last character. If there's more that your formatting needs to do, you should describe it.
the string will only contain 4 digits, but every time i load that string from db and print it i want to format it to the specific one with a whitespace before last character.

your example works fine, but i needed to change it to preg_replace('/.$/', ' 1', $yourstring). one more think how can i change it so i can format any other string like "5432". :roll:

thanks in advance

Re: format string

Posted: Tue Aug 05, 2008 11:57 am
by chaos
Ahh, sorry, should've been preg_replace('/.$/', ' $0', $yourstring).

Re: format string

Posted: Tue Aug 05, 2008 12:00 pm
by bouncer
works just fine, thanks :D

regards

Re: format string

Posted: Tue Aug 05, 2008 1:45 pm
by bouncer
one more think, is it possible that instead of using a string like "0001", use 0001 as a integer value, without loosing the left zeros, and then format this value to 000 1 or 099 6 ?

because in my code i have

Code: Select all

 
$nrDoc = "0001";
 
// query here to check if this doc already exists, if exists increment the nrDoc by 1
$nrDoc++;
 
my problem is when i increment that value. :cry:

regards

Re: format string

Posted: Tue Aug 05, 2008 2:00 pm
by chaos

Code: Select all

$fmt = sprintf('%04d', $num);

Re: format string

Posted: Wed Aug 06, 2008 1:56 am
by RobertGonzalez
You might also want to have a look at number_format(), though I suspect you are going to have to change your logic. It started out that you were manipulating a string and changed to you dealing with numeric values. You can always cast the number to a string then massage it there. And regular expressions are overkill for what you are doing. If you only want the last number of the string to be padded you can use simple string manipulation functions to do that.

Code: Select all

<?php
$str = 'dfgh';
$str = trim(chunk_split($str, 3, ' '));
var_dump($str);
 
// output "dfg h"
?>

Re: format string

Posted: Wed Aug 06, 2008 4:01 am
by bouncer
thanks once again, that realy helped me, now everything is working just fine. :wink:

regards