How to remove all leading zeros in a string in PHP ?
Last Updated :
20 Sep, 2019
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
$str = "00775505" ;
$str = ltrim( $str , "0" );
echo $str ;
?>
|
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
$str = "00775505" ;
$str = (string)((int)( $str ));
echo $str ;
?>
|
Share your thoughts in the comments
Please Login to comment...