How to remove all leading zeros in a string in PHP: solved
In this tutorial, we will be showing you how to remove all preceding zeros in a string in PHP.
Example:
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.
<?php
// Store the number string with
// leading zeros into variable
$str
=
"00957606"
;
// 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:
957606
Method 2: First convert the given string into a 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 = "00995505" ; // First typecast to int and // then to string $str = (string)((int)( $str )); // Display the result echo $str ; ?> |
Output:
995505