I'd like to format given string with following rules;
Get only digits out of it
Get them in 4 digit groups
Each group must lead with 0's
There must be 3 groups.
Given : 1234 Expected Result: 0000-0000-1234
Given : 123 Expected Result: 0000-0000-0123
Given : 12345 Expected Result: 0000-0001-2345
Given : 123456789012345 Expected Result: 1234-5678-9012
Is there anyway to achieve this without getting into creating a method / function for it? Such as with regex and / or using sprintf?
Use str_pad() to format the strings with all zeros, and chunk_split() to add a - for every 4 characters, substr() is responsable for limit the lenght of string at 14 characters, in the last example the string have 16 characters, substr() fix this.
$arr = ['1234', '123', '12345', '123456789012345'];
foreach($arr as $item){
$str = str_pad($item, 12, '0',STR_PAD_LEFT);
echo substr(chunk_split($str, 4, '-'), 0, 14) .'<br>';
}
Output:
0000-0000-1234
0000-0000-0123
0000-0001-2345
1234-5678-9012
You can use vsprintf, a much simpler approach
<?php
$no_arr = ['1234', '123', '12345', '123456789012345'];
foreach($no_arr as $n){
echo vsprintf("%04d-%04d-%04d",str_split(sprintf("%012d", $n), 4))."<br/>";
}
Output will be:
0000-0000-1234
0000-0000-0123
0000-0001-2345
1234-5678-9012
Just format the string using sprintf, split it and then implode!
<?php
$no_arr = ['1234', '123', '12345', '123456789012345'];
foreach($no_arr as $n){
$formatted_number = str_split(sprintf("%012d", $n), 4);
echo substr(implode("-", $formatted_number), 0, 14) .'<br>';
}
Output will be:
0000-0000-1234
0000-0000-0123
0000-0001-2345
1234-5678-9012
Explanation:
$twelve_digit = sprintf("%012d", $n);
$split_into_4 = str_split($twelve_digit, 4);
$add_hyphen = implode("-", $split_into_4);
$remove_trailing_chars = substr($add_hyphen, 0, 14);
echo $remove_trailing_chars ." <br/>";
One Liner:
echo substr(implode("-", str_split(sprintf("%012d", $n), 4)), 0, 14);
Related
I'm trying to replace the first 4 digits of a number with X, for example:
$num= 1234567890
I want the output to appear like this: XXXX567890
I have tried the function:
$new = substr($num, 0, -4) . 'xxx';
but It only removes the last 4 digits so what should I do ?
You can use the same in opposite
$num= 1234567890;
$new = 'xxxx' . substr($num, 4);
echo $new;
second parameter tells about starting point for string and parity(positive or negative) tells about direction. positive number means to right of string and negative number means to left of string.
http://php.net/manual/en/function.substr.php
With substr_replace function:
$num = 1234567890;
print_r(substr_replace($num, 'XXXX', 0, 4)); // XXXX567890
Another solution is to use str_pad which "fills up" the string to 10 elements with "X".
$num= 1234567890;
Echo str_pad(substr($num,4), 10, "X",STR_PAD_LEFT);
https://3v4l.org/tKtB7
Or if the string lenght is not always 10 use:
Echo str_pad(substr($num,4), strlen($num), "X",STR_PAD_LEFT);
I think this one can be helpful for achieving desired output.
Solution 1:
Try this code snippet here
<?php
ini_set('display_errors', 1);
$num= 1234567890;
echo "XXXX".substr($num, 4);//concatenating 4 X and with the substring
Solution 2: Try this code snippet here
<?php
ini_set('display_errors', 1);
$num= 1234567890;
$totalDigits=4;
echo str_repeat("X", $totalDigits).substr($num, $totalDigits);// here we are using str_repeat to repeat a substring no. of times
Output: XXXX567890
If have written a tiny function to do tasks like this.
function hide_details($str, $num = 4, $replace = 'x') {
return str_repeat($replace, $num).substr($str, $num);
}
echo hide_details('1234567890');
How can I get the first and the last digit of a number? For example 2468, I want to get the number 28. I am able to get the ones in the middle (46) but I can't do the same for the first and last digit.
For the digits in the middle I can do it
$substrmid = substr ($sum,1,-1); //my $sum is 2468
echo $substrmid;
Thank you in advance.
You can get first and last character from string as below:-
$sum = (string)2468; // type casting int to string
echo $sum[0]; // 2
echo $sum[strlen($sum)-1]; // 8
OR
$arr = str_split(2468); // convert string to an array
echo reset($arr); // 2
echo end($arr); // 8
Best way is to use substr described by Mark Baker in his comment,
$sum = 2468; // No need of type casting
echo substr($sum, 0, 1); // 2
echo substr($sum, -1); // 8
You can use substr like this:
<?php
$a = 2468;
echo substr($a, 0, 1).substr($a,-1);
You can also use something like this (without casting).
$num = 2468;
$lastDigit = abs($num % 10); // 8
However, this solution doesn't work for decimal numbers, but if you know that you'll be working with nothing else than integers, it'll work.
The abs bit is there to cover the case of negative integers.
$num = (string)123;
$first = reset($num);
$last = end($num);
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'), '.');
?>
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);
This question already has answers here:
How to pad single-digit numbers with a leading 0
(7 answers)
Closed 11 months ago.
I have an integer that I need to convert into a 4 digits string. I know the integer number is between 1 and 9999. If the number is 4, I want the output string to be "0004". If the number is 134, I need the string output as "0134" and so on.
What would be the shortest most elegant way of achieving this in PHP? Thank you.
I would use sprintf():
$string = sprintf( "%04d", $number);
Using this demo:
foreach( array( 4, 134) as $number) {
$string = sprintf( "%04d", $number);
echo $string . "\n";
}
You get as output:
0004
0134
Try this
$num = 1;
$paddedNum = sprintf("%04d", $num);
echo $paddedNum;
Try this
str_pad($input, 4, "0", STR_PAD_LEFT);
This will work for integer and string both
http://php.net/manual/de/function.str-pad.php
$input = 9;
$str = str_pad($input, 4, "0", STR_PAD_LEFT); //results in 0009
You can use sprintf with the %d option:
$NewString = sprintf( "%04d", $OldNumber);
the 04 tells sprintf how many digits your number should be, and will fill with zeros if it doesn't reach that number.
$num = rand(1,9999);
echo sprintf( "%04d", $num);
Try this.