Open In App

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

Last Updated : 20 Sep, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number in string format and the task is to remove all leading zeros from the given string in PHP.

Examples:

Input : str = 00006665555
Output : 6665555

Input : str = 00775505
Output : 775505

Method 1: Using 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");

Program:




<?php
  
// Store the number string with
// leading zeros into variable
$str = "00775505";
  
// 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:

775505

Method 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.

Program:




<?php
  
// Store the number string with
// leading zeros into variable
$str = "00775505";
  
// First typecast to int and 
// then to string
$str = (string)((int)($str));
          
// Display the result
echo $str;
  
?>


Output:

775505

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads