This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Format number in PHP
I want my number format 12 char in length, like if there is value 12 it should output 000000000012
Example: if value is 123.50 it should output 000000012350 No decimal (multiple of 100)
Any idea, which function will be used?
Thanks !
You can use str_pad
echo str_pad(12, 12, "0", STR_PAD_LEFT);
You can also use printf or sprintf
printf("%012s", 12);
Output
000000000012
Some Work Arounds
var_dump(formatOutput("12"));
var_dump(formatOutput("123.50"));
var_dump(formatOutput("123.378201"));
function formatOutput($no,$max = 15) {
$no = str_pad("1", strlen(substr(strrchr($no, "."), 1)), "0", STR_PAD_RIGHT) * $no;
if(strpos($no, "."))
$no = str_replace(".", "", $no) . "0" ;
return str_pad($no, $max, "0", STR_PAD_LEFT);
}
Output
string '000000000000012' (length=15)
string '000000000001235' (length=15)
string '000001233782010' (length=15)
See str_pad() http://php.net/manual/en/function.str-pad.php
string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )
This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.
input
The input string.
pad_length
If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place.
pad_string
The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length.
pad_type
Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.
sprintf();
Check php manual sprintf() function in php.net
Along with printf()can do the job. Check example 7 in the link above.
Related
This question already has answers here:
PHP and preg_match Regex to pull number with decimal out of string
(4 answers)
Closed 4 years ago.
I am trying to extract digits and decimal point from a string but the decimal point is lost when I am using following regular expression:
<?php
$str = "$40.0000";
echo $str;
echo "<br />";
$pattern = "/\D+/";
$str = preg_replace($pattern, '', $str);
echo $str;
?>
Output:
$40.0000
400000
I want to retain dot also. How to include dot in my regex?
<?php
$str = '$40000.00';
echo preg_replace('/[^\d.]/','',$str);
Several good answers here, too: How do I convert output of number_format back to numbers in PHP?
There are two appropriate functions for this purpose. The first, round(), rounds a value to a specified number of decimal places. The function’s first argument is the number to be rounded. This can be either a number or a variable with a number value. The second argument is optional; it represents the number of decimal places to round to. For example:
round (4.30); // 4
round (4.289, 2); // 4.29
$num = 236.26985;
round ($num); // 236
The other function you can use in this situation is number_format(). It works like round() in that it takes a number (or a variable with a numeric value) and an optional decimal specifier. This function has the added benefit of formatting the number with commas, the way it would commonly be written:
number_format (428.4959, 2); // 428.50
number_format (428, 2); // 428.00
number_format (123456789); // 123,456,789
I am trying to limit the characters of a string. Additionally, if the string is less than the required characters, I want to add padding to it.
function create_string($string, $length) {
$str_len = strlen($string);
if($str_len > $length) {
//if string is greater than max length, then strip it
$str = substr($string, 0, $length);
} else {
//if string is less than the required length, pad it with what it needs to be the length
$remaining = $length-$str_len;
$str = str_pad($string, $remaining);
}
return $str;
}
My input is
"Nik's Auto Salon"
which is 16 characters. The second parameter is 40.
However, This string is returned
"Nik's Auto Salon "
which has only eight characters of padding added onto it. That doesn't seem right.
I also tried this string:
Gold Package Mobile Car Detail
With this input, it returns a string with NO padding added onto it. When that phrase is shorter than the required 45 length I put in the second parameter place.
How can I make this function work according to my specifications?
str_pad doesn't add spaces equal to its second parameter, it pads the string TO the length given in the second parameter. This isn't very clear even in the documentation.
Try this instead (and take out the line where you calculate $remaining):
$str = str_pad($string, $length);
This question already has answers here:
Zero-pad digits in string
(5 answers)
Closed 11 months ago.
I need to have a string that has a specified length and replace the excess characters with a letter.
e.g.
My original string is : "JOHNDOESMITH". The length should be up to 25 characters only.
I need my string to become "XXXXXXXXXXXXXJOHNDOESMITH" (13 X's and 12 chars from the original string).
Anybody please tell me how to achieve this? Is there a string function for this? I've been racking my brains out for quite some time now and I still can't find a solution.
You could use str_pad() to do it...
echo str_pad($str, 25, 'X', STR_PAD_LEFT);
CodePad.
You could use str_repeat() to do it...
echo str_repeat('X', max(0, 25 - strlen($str))) . $str;
CodePad.
The length should be up to 25 characters only.
You can always run substr($str, 0, 25) to truncate your string to the first 25 characters.
We can use printf() or sprintf() function.
$format= "%'X25s";
printf($format, "JOHNDOESMITH"); // Prints a formatted string
$output = sprintf($format, "JOHNDOESMITH"); // Returns a formatted string
Use the str_pad function:
$a="JOHNDOESMITH";
$b=str_pad($a,25,'X',STR_PAD_LEFT);
print_r($b);
I am doing a real estate feed for a portal and it is telling me the max length of a string should be 20,000 bytes (20kb), but I have never run across this before.
How can I measure byte size of a varchar string. So I can then do a while loop to trim it down.
You can use mb_strlen() to get the byte length using a encoding that only have byte-characters, without worring about multibyte or singlebyte strings.
For example, as drake127 saids in a comment of mb_strlen, you can use '8bit' encoding:
<?php
$string = 'Cién cañones por banda';
echo mb_strlen($string, '8bit');
?>
You can have problems using strlen function since php have an option to overload strlen to actually call mb_strlen. See more info about it in http://php.net/manual/en/mbstring.overload.php
For trim the string by byte length without split in middle of a multibyte character you can use:
mb_strcut(string $str, int $start [, int $length [, string $encoding ]] )
You have to figure out if the string is ascii encoded or encoded with a multi-byte format.
In the former case, you can just use strlen.
In the latter case you need to find the number of bytes per character.
the strlen documentation gives an example of how to do it : http://www.php.net/manual/en/function.strlen.php#72274
Do you mean byte size or string length?
Byte size is measured with strlen(), whereas string length is queried using mb_strlen(). You can use substr() to trim a string to X bytes (note that this will break the string if it has a multi-byte encoding - as pointed out by Darhazer in the comments) and mb_substr() to trim it to X characters in the encoding of the string.
PHP's strlen() function returns the number of ASCII characters.
strlen('borsc') -> 5 (bytes)
strlen('boršč') -> 7 (bytes)
$limit_in_kBytes = 20000;
$pointer = 0;
while(strlen($your_string) > (($pointer + 1) * $limit_in_kBytes)){
$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
// here you can handle (0 - n) parts of string
$pointer++;
}
$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
// here you can handle last part of string
.. or you can use a function like this:
function parseStrToArr($string, $limit_in_kBytes){
$ret = array();
$pointer = 0;
while(strlen($string) > (($pointer + 1) * $limit_in_kBytes)){
$ret[] = substr($string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
$pointer++;
}
$ret[] = substr($string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
return $ret;
}
$arr = parseStrToArr($your_string, $limit_in_kBytes = 20000);
Further to PhoneixS answer to get the correct length of string in bytes - Since mb_strlen() is slower than strlen(), for the best performance one can check "mbstring.func_overload" ini setting so that mb_strlen() is used only when it is really required:
$content_length = ini_get('mbstring.func_overload') ? mb_strlen($content , '8bit') : strlen($content);
echo intval(chr(255));
I don't understand...
The chr() function turns a byte into its ASCII equivalent and intval() function gets the integer value of a variable.
If we were to break the statement into two different lines, this would be:
$a = chr(255); // $a is now a string
echo intval($a);
If you check intval()'s documentation you will notice that:
Strings will most likely return 0
although this depends on the leftmost
characters of the string. The common
rules of integer casting apply.
That's why the result is zero.
The byte 0xFF does not represent a digit in either octal, decimal or hexadecimal what intval is looking for. You probably wanted the ord function.
To output 255, you need:
echo intval(ord(chr(255)));
There are 128 ordinal numbers in ASCII, the 255 comes out to be ÿ so when you convert it to a number with intval, it will be 0.
Because chr delivers a string, in this case with just one character, the character 0xFF, or better known as ÿ.
intval on the other hand does a conversion from a string to an integer based on the content of the string, and not the characters.
echo intval("33"); // will print 33
echo intval("10", 8); // will print 8
echo intval("0xFF", 16); // will print 255
echo intval("m"); // will print zero...
//you can't convert letters like that to numbers.
chr(255)
returns a character corresponding to ASCI 255
and intval try to bring out integer part from a variable
since chr(255) returns a non-numeric character so intval get no int value and return 0