format string
Moderator: General Moderators
format string
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
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
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
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.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.
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".
thanks in advance
Re: format string
Ahh, sorry, should've been preg_replace('/.$/', ' $0', $yourstring).
Re: format string
works just fine, thanks
regards
regards
Re: format string
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
my problem is when i increment that value.
regards
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++;
regards
Re: format string
Code: Select all
$fmt = sprintf('%04d', $num);- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Re: format string
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
thanks once again, that realy helped me, now everything is working just fine.
regards
regards