Thursday 13 February 2020

PHP string manipulation

Get length of a number
$num = 245354;
$numlength = strlen((string)$num);
https://stackoverflow.com/questions/28433798/php-get-length-of-digits-in-a-number
Formatting a number with leading 0s 
SPRINTF
sprintf('%05d', 1); // Add 4 0s to 1 make it a string of length 5, with '00001'
sprintf('%02d', 11); // No 0s will  be added as 11 is already length of 2, produces'11'

STRPAD
$input "Alien";
echo str_pad($input10);                      // produces "Alien     ", total 10 characters, Alien is 5 characters, produces another 5 character of white spacesecho str_pad($input10"-="STR_PAD_LEFT);  // produces "-=-=-Alien"echo str_pad($input10"_"STR_PAD_BOTH);   // produces "__Alien___"echo str_pad($input,  6"___");               // produces "Alien_"echo str_pad($input,  3"*");                 // produces "Alien"
str_pad('', 20); // produces a white space of length 20 '                 '
https://www.php.net/manual/en/function.str-pad.php
https://stackoverflow.com/questions/1699958/formatting-a-number-with-leading-zeros-in-php/55688659

No comments:

Post a Comment