I'm trying to replace some characters from a string using str_pad and I can't get it to work at all and I have no idea why it doesn't work.
Code:
<?php
$t = "abcdefghij";
$t = str_pad($t, 4, "0");
echo $t;
?>
Expected:
abcd000000
Result:
abcdefghij
I also tried:
$t = sprintf("%04x", $t);
Which results in:
0000
If you have a variable length string, you can use the below
$str = "abcdefghijzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
$head = substr($str, 0, 4); // construct the first part of your string
$tail = substr($str, 4); // get the second part of the string
print $head . str_repeat('0',strlen($tail));
// or all in one go
$number = 4;
print substr($str, 0, $number) . str_repeat('0',strlen(substr($str, $number)));
//will output
//abcd0000000000000000000000000000000000000
To replace everything except the first x number of characters in your string.
Because your string is longer than four characters so str_pad() will not append anything to it.
If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place, and input will be returned.
If you want to always append four zeros just concatenate them onto your string:
<?php
$t = "abcdefghij";
$t = '0000' . $t;
echo $t;
?>
What you are looking for is a mixture of str_pad and substr, using the two like this:
echo str_pad(substr($str, 0, 4), strlen($str), '0', STR_PAD_RIGHT);
Will give you output like this:
abcd000000
You may however, need to tweak the numbers to get your desired results.
Here is a function you can use:
function pad($str, $length, $value= '0', $side = STR_PAD_RIGHT){
return str_pad(substr($str, 0, $length), strlen($str), $value, $side);
}
echo pad('abcdefghij', 4);
You need a different functions. str_pad() adds to the string and you are wanting to replace:
$t = substr_replace($t, str_repeat('0', strlen($t)-4), 4);
Related
I have variables of bitcoin values all rounded to 8 decimal places. eg
1.00645600
I need a way in jQuery or php to get the whole number [1], The decimal values [006456], and trailing zeros [00]. I have already tried php substr but it messed up with the results since im dealing with variables.
Simple and general solution in PHP without involving regular expressions (that is an option also):
$number = '1.00645600';
$flooredNumber = floor($number); // 1
$decimalPart = (string) (floatval($number) - $flooredNumber); // 0.006456
$decimals = str_replace('0.', '', $decimalPart); // 006456
$trailingZeros = str_replace(rtrim($number, '0'), '', $number); // 00
substr
Returns the portion of string specified by the start and length parameters.
http://php.net/manual/en/function.substr.php
If the numbers in your string are always in the same position you can use substr() to get the desired values:
$str = '1.00645600';
echo substr($str, 0, 1)."\r\n";
echo substr($str, 2, 2)."\r\n";
echo substr($str, 2, 6)."\r\n";
Output:
1
00
006456
Perhaps, this way?
<?php
$i = '1.00645600';
echo rtrim(rtrim($i, '0'), '.');
?>
PLease look my php code. I dont want rmeoving zeros.
<?php
$number = '00154';
$next = $number + 1;
echo $next; // returns 155
?>
But I want to return 00155
Use str_pad() in conjunction with strlen(). strlen() gets the number of digits, and then uses that as the pad length for str_pad().
$next = str_pad($next, strlen($number), '0', STR_PAD_LEFT);
If you always want a fixed length, say 5, then this becomes shorter:
$next = sprintf('%05d', $next);
Demo
You can do that with str_pad if your number length is constant. In your case you have 5 length number. You can get length of number first and you can fill up zeros in result;
<?php
$number = '00154';
$length = strlen($number);
$next = $number + 1;
echo str_pad($next, $length, "0", STR_PAD_LEFT);
?>
Here is a working demo: codepad
00155 and 155 is from a maths perspective EQUAL.
echo str_pad($next, 5, '0', STR_PAD_LEFT);
fills left side with zeroes.
This is because your number is a string. Convert it to a number (integer or float) first, the use math function.
This is a tricky one: I want to add +1 to this number: 012345675901 and the expected result is: 012345675902. Instead I get: 2739134 when I do this:
echo (012345675901+1);
When I try:
echo ('012345675901'+1);
I get this: 12345675902 which is pretty close to what I need, but it removes the leading zero.
When I do this:
echo (int) 012345675901;
I get 2739133. I also tried bcadd() without success:
echo bcadd(012345675901, 1);
which resulted in 2739134.
I know I am missing something here. I would really appreciate your help!
UPDATE 1
Answer 1 says that the number is octal:
function is_octal($x) {
return decoct(octdec($x)) == $x;
}
$number = is_octal(012345675901);
echo var_dump($number);
The above returns false. I thought I needed to convert this from octal to a normal string but didn't work. I can't avoid not using the above number - I just need to increment it by one.
EDIT 2
This is the correct code:
$str = '012345675901';
$str1 = ltrim($str, '0'); // to remove the leading zero
$str2 = bcadd($str1, 1); // +1 to your result
$str3 = strlen($str); // get the length of your first number
echo str_pad($str2, $str3, '0', STR_PAD_LEFT); // apply zeros
Thank you everyone for your help! The above code produces: 012345675902 as expected
The leading 0 is treating your number as octal.
The leading 0 you need for output as a string, is a purely a representation.
please see the code for explanation.
$str = "012345675901"; // your number
$str1 = ltrim($str, '0'); // to remove the leading zero
$str2 = bcadd($str1, 1); // +1 to your result
$str3 = strlen($str); // get the length of your first number
echo str_pad($str2, $str3, '0', STR_PAD_LEFT); // apply zeros
I have a string, its content is "24896". Now I want to add some zeros to the left, so I tried:
$test = str_pad($myString, 4, "0", STR_PAD_LEFT);
The result is "24896" again, no zeros added to the left. Am I missing something here?
Thanks!
The second argument to str_pad() takes the full length of the final string; because you're passing 4 and the length of $myString is 5, nothing will happen.
You should choose a width that's at least one bigger than your example value, e.g.:
str_pad($myString, 9, '0', STR_PAD_LEFT);
// "000024896"
Update
This might be obvious, but if you always want 4 zeros in front of whatever $myString is:
'0000' . $myString;
Because you're padding it to length 4, and your string 24896 is 5 characters long, hence it doesn't need to pad anything as it's already more than 4 characters long.
The second parameter in the str_pad function is the new length of the string.
Try
$myString = "24896" ;
$test = str_pad($myString, strlen($myString) + 4, "0", STR_PAD_LEFT);
echo $test;
Output
000024896
Just make the pad first and attach it, presuming you don't know how long it is. No need to calculate the length of the original string:
$x = 4;
$pad = str_pad('', $x, '0');
$test = $pad.$myString;
Or better
$x = 4;
$test = str_pad('', $x, '0').$myString;
The length you specified in the str_function is less than the input string read documentation properly
try this it will work for you
Your String is 5 character
e.g $myString=24896;
Now you want to add 5 zero to the left
then your length will be you string + 5 the actual is 5+5=10;
Now pass this to the function your function will be like this
$test = str_pad($myString, 10, "0", STR_PAD_LEFT);
echo $test;
OUTPUT:
0000024896
how many no zero you want to add? no zeros added because padding length is smaller than your given $myString length.
Please try this one
$number = 24896;
$number = sprintf('%06d', $number);
echo $number;
or use this one
$number = 24896;
$number = str_pad($number, 6, '0', STR_PAD_LEFT);//here 6 is padding length
echo $number;
output
024896
I got a string value in number, like 2345.567, I want to keep only one character after the decimal. I dont want to use any Number function, I just want to remove any number of character after the period (dot)?
If you are worried about the input being not a number, you should validate it first:
function round_number($number, $precision = 1) {
if(!is_numeric($number)) {
throw new InvalidArgumentException("round_number() expects a numeric type, instead received '".gettype($number)."'");
}
return round($number, $precision);
}
Reference:
round($number, $precision)
is_numeric($var)
$number = 2345.567;
$new_numb = number_format($number,1);
$new_numb will be treated as string
<?php
$str = "2345.567";
$ip = explode('.',$str);
echo $ip[0].".".substr($ip[1],0,1)
?>
after edit:
<?php
// case: if there is no decimal place
echo $ip[0]."".($ip[1]?".".substr($ip[1],0,1):'');
?>
Formatted string output can be done with number_format or with the printf family of functions.
print number_format((float)$string, 1);
printf("%.1f", $string);
Assuming the input is guaranteed to be well-formed...
substr($numberString, 0, strpos(".", $numberString) + 2);
You can do it as follows
$string = "234567.2345";
if(!is_numeric($string)) {
$output = $string;
}
else{
$output = round($string,1);
}
output will be
234567.2
if string is given as 234
output will be 234.o
if string is given other than number "asdf"
output will be asdf