How to remove all leading zeros in a string in PHP ?

PHP

Nicesnippets

383

23-11-2020


Hi Guys,

In this example,I will learn you how to remove all leading zeros in a string in php.you can easy and simply remove all leading zeros in a string in php.

Example 1: ltrim() function


The ltrim() function is used to remove whitespaces or other characters (if specified) from the left side of a string

Syntax:

ltrim( "string", "character which to be remove from the left side of string");

<?php

// Store the number string with

// leading zeros into variable

$str = "00858086";

// Passing the string as first

// argument and the character

// to be removed as second

// parameter

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

// Display the result

echo $str;

?>

Output:

858086

Example 2:

First convert the given string into number typecast the string to int which will automatically remove all the leading zeros and then again typecast it to string to make it string again.

<?php

// Store the number string with

// leading zeros into variable

$str = "00655055";

// First typecast to int and

// then to string

$str = (string)((int)($str));

// Display the result

echo $str;

?>

Output:

655055

It will help you...