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

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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;
  
?>

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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;
  
?>

chevron_right


Output:

775505


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.