Trim any zeros at the beginning of a string using PHP - php

Users will be filling a field in with numbers relating to their account. Unfortunately, some users will have zeroes prefixed to the beginning of the number to make up a six digit number (e.g. 000123, 001234) and others won't (e.g. 123, 1234). I want to 'trim' the numbers from users that have been prefixed with zeros in front so if a user enters 000123, it will remove the zeroes to become 123.
I've had a look at trim and substr but I don't believe these will do the job?

You can use ltrim() and pass the characters that should be removed as second parameter:
$input = ltrim($input, '0');
// 000123 -> 123
ltrim only removes the specified characters (default white space) from the beginning (left side) of the string.

ltrim($usernumber, "0");
should do the job, according to the PHP Manual

$number = "004561";
$number = intval($number, 10);
$number = (string)$number; // if you want it to again be a string

You can always force PHP to parse this as an int. If you need to, you can convert it back to a string later
(int) "000123"

You can drop the leading zeros by converting from a string to a number and back again. For example:
$str = '000006767';
echo ''.+$str; // echo "6767"

Just multiply your number by zero.
$input=$input*1;
//000000123*1 = 123

Related

Why trim zeros from decimal part php not accurate for .00?

I have this float value 1290.00 and I would like to trim the zeros on the right in the cleanest way to get 1290, but Why I got 129 if using trim function?
Code:
<?php
$var = '1290.00';
printf ("value: %s -> %s\n", $var, trim($var, '.00'));
The output:
value: 1290.00 -> 129
I have seen different solutions to it by not using trim function, but why is trim not working? I also tried with GoLang and got the same behavior.
Trim removes characters from the end, individually, not as a phrase. It removes all found characters until it can't find any more in the list. So it removes the 0, the 0, the period, then the 0. In this case, I would recommend either round or number_format
number_format($var, 0, '', ''); // 1290
trim doesn't work like that. You only specify the characters you want to trim once, and two periods are used to specify a range. It will then trim all of those characters from the end.
A more efficient method might be intval($var)
Depending on your usage, note that number_format() also rounds the value (see the first example of the documentation). If you need to truncate the number you could use floor():
number_format(1.9, 0, '', ''); // string(1) "2"
floor(1.9); // 1

Trim the first digit of a Phone number to be in International format

Am working on a web application whereby am capturing phone number from the user, but on the backend (build in Laravel PHP) I want to trim the first digit from the phone number and replace it with 254.
For instance,, am capturing this phone number 07******23**
I need to replace the first zero with 254 so that it can be 2547******23**
You don't even need to invoke regex here, substr() should work just fine:
$input = "07123456789";
$output = "254" . substr($input, 1);
If you only want to do this replacement on numbers beginning with zero, then it might make more sense to use preg_replace:
$output = preg_replace("/^0/", "254", $input);
Use ltrim to remove the zero.
It will remove the zero if it's there, and leave the string intact if not.
echo "254" . ltrim($number, "0");
See example with and without the leading zero:
https://3v4l.org/Z03st

Find and split a string by the first character that is not 0

I wanted to know how I could split a string based on the first character that is not 0, e.g.
$ID = ABC-000000160810;
I want to split the id so it looks like this:
$split_ID = 160810;
I tried to just get the last 6 digits, however the problem was that the 6 digits might not always be consistent, so just need to split based on the first non-zero. What is the easiest way to achieve this?
Thanks.
Here's a way using a regular expression:
$id = 'ABC-000000160810';
preg_match('/-0*([1-9][0-9]*)/', $id, $matches);
$split_id = $matches[1];
You can use ltrim if you only want to remove leading zeroes.
$ID = ABC-000000160810;
$split_ID = ltrim($str, '0');
Use ltrim to remove leading characters.
$id = 'ABC-00001234';
$numeric = ltrim(mb_substr($id, mb_strpos($id, '-') + 1), '0');
echo $numeric; // 1234
The above requires the mbstring extension to be enabled. If you encounter an error, either enable the extension or use the non-multibyte functions substr and strpos. Probably you should get in the habit of using the mb_ string functions.
This should also work:
const CHAR_MASK = 'a..zA..Z-0';
$id = 'ABC-00001234';
$numeric = ltrim($id, CHAR_MASK);
echo $numeric; // 1234
For your example "ABC-00000016081" you might use a regex that would match the first part up until you encounter not a zero and then use \K to not include the previously consumed characters in the final match.
[^-]+-0+\K[1-9][0-9]+
[^-]+ Match not a - one or more times using a negated character class
- Match literally
0+ Match one or more times a zero (If you want your match without leading zeroes you could use 0*)
\K Resets the starting point of the reported match
[1-9][0-9]* Match your value starting with a digit 1 -9
Test
You can substr off the ABC part and multiply with 1 to make it a number.
$ID = "ABC-000000160810";
Echo substr($ID, 4)*1;

Keep leading zeros with fgetcsv in PHP

I'm reading a .csv file (I have no control of the format of the file) and I'm trying to keep the leading zeros for the data in the resulting array. For instance, the .csv file has "0615" in a field, but resulting array contains "615". There are also fields in the .csv file that do not contain leading zeros, so adding zeros to the beginning of each field will not work.
I've tried to force functions to read the fields as a string, but explode, str_getcsv, fgetcsv all parse it as an integer and remove the leading zero beforehand. Any thoughts?
Edit: explode does NOT remove the leading zeros. Using explode with fgets works.
explode() works on a string basis; your type conversion must be happening elsewhere:
$data = "00555,00666,00777,00888";
$a = explode(",",$data);
foreach($a as $b) echo $b . " "; // 00555 00666 00777 00888
Use (string)$b if PHP insists on interpreting the strings as integers.
If you need the leading zeroes for presentation or uniform formatting processes then it might be easier to simply pad the numbers when you output them.
http://php.net/manual/en/function.str-pad.php should be of help here.
Use str_pad to add the leading zeros to the parsed integer, wherever you need it.
Or use sprintf, if you are familiar with it.
$num = 1;
$num = sprintf('%04d', $num);
// ^^
// ||_ How many leading digits?
// |_ Leading digit?
// output: 0001

Selecting a random character froma string in PHP

I'm creating a security system in PHP which requires the user to enter a certain character from their unique security key, I was wondering how it is possible to make php return a selected character from a string.
For example, the security code is 1234567, I want php to randomly select 1 character from this string, and then compare that character to the character asked for in the security process
$number = rand(1,7);
// The number = 7
E.G, please enter the 7th character of your security code.
//script to return the 7th character in the string and compare it to the entered character.
Thanks in advance :)
$randomIndex = mt_rand(0, strlen($securityCode) - 1);
$randomChar = $securityCode[$randomIndex];
This creates a random number (mt_rand) between 0 and the last index of your string (strlen($securityCode) - 1). If your string is 10 characters long, that's a number between 0 and 9. It then takes the character at that index.
Try substr, strlen and rand
$numbers = rand(0,strlen($securitycode) - 1);
$randChar = substr($securitycode, $numbers, 1);
Then compare..

Categories