w3resource

PHP String Exercises : Remove all leading zeroes from a string


19. Remove Leading Zeroes from a String

Write a PHP script to remove all leading zeroes from a string.

Original String : '000547023.24'

Visual Presentation:

PHP String Exercises: Get the first word of a sentence

Sample Solution:

PHP Code:

<?php
$x = '000547023.24';
// Define the original string.

$str1 = ltrim($x, '0');
// Remove leading zeros from the string.

echo $str1."\n";
// Output the modified string.
?>

Output:

547023.24

Explanation:

The above PHP code snippet takes the string '000547023.24' and removes any leading zeros from it using the "ltrim()" function. The "ltrim()" function trims characters from the left side of a string. Here, it trims leading zeros from the string '000547023.24', resulting in the string '547023.24'. Finally, it echoes out the modified string.

Flowchart :

Flowchart: Remove all leading zeroes from a string

For more Practice: Solve these Related Problems:

  • Write a PHP script to strip all leading zeros from a numeric string using ltrim() and then cast it to a number.
  • Write a PHP function to remove any zero-padding from a string representing a number and return the cleaned string.
  • Write a PHP program to iterate over a numeric string, remove leading zeroes manually using a loop, and output the result.
  • Write a PHP script to compare a string with leading zeros and its integer conversion to ensure proper removal of extra zeros.

Go to:


PREV : Get First Word of a Sentence.
NEXT : Remove Part of a String.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.