Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all leading zeroes in a string

Tags:

string

php

People also ask

How do you remove leading zeros from a string?

Use the inbuilt replaceAll() method of the String class which accepts two parameters, a Regular Expression, and a Replacement String. To remove the leading zeros, pass a Regex as the first parameter and empty string as the second parameter. This method replaces the matched value with the given string.

How do you remove leading zeros from a string in Python?

Use the lstrip() Function Along With List Comprehension to Remove Leading Zeros in a String in Python. The lstrip() can be utilized to remove the leading characters of the string if they exist. By default, a space is the leading character to remove in the string.

How do you remove leading zeros from a string in C++?

str. erase(0, min(str. find_first_not_of('0'), str. size()-1));

How do you remove leading zeros from a list in Java?

You can remove the leading zeros by just searching for the first non-zero value, and then clearing the preceding sublist: Iterator<Integer> it = list. iterator(); int i = 0; while (it. hasNext() && it.


ltrim:

$str = ltrim($str, '0');

(string)((int)"00000234892839")

Don't know why people are using so complex methods to achieve such a simple thing! And regex? Wow!

Here you go, the easiest and simplest way (as explained here: https://nabtron.com/kiss-code/ ):

$a = '000000000000001';
$a += 0;

echo $a; // will output 1

Similar to another suggestion, except will not obliterate actual zero:

if (ltrim($str, '0') != '') {
    $str = ltrim($str, '0');
} else {
    $str = '0';
}

Or as was suggested (as of PHP 5.3), shorthand ternary operator can be used:

$str = ltrim($str, '0') ?: '0'; 

you can add "+" in your variable,

example :

$numString = "0000001123000";
echo +$numString;

Regex was proposed already, but not correctly:

<?php
    $number = '00000004523423400023402340240';
    $withoutLeadingZeroes = preg_replace('/^0+/', '', $number)
    echo $withoutLeadingZeroes;
?>

output is then:

4523423400023402340240

Background on Regex: the ^ signals beginning of string and the + sign signals more or none of the preceding sign. Therefore, the regex ^0+ matches all zeroes at the beginning of a string.