ltrim()
Our article is about the PHP function ltrim(), which is used to remove whitespace or other specified characters from the beginning of a string. This function is
The PHP ltrim() function removes whitespace (or other specified characters) from the left side — the beginning — of a string. The "l" stands for left. It is the counterpart of rtrim(), which strips from the right, and trim(), which strips from both ends.
ltrim() is most useful when you need to normalize input you don't fully control: leading spaces from form fields, leading zeros in identifiers, or leading separators left over after splitting or concatenating strings.
Syntax
ltrim(string $string, string $characters = " \n\r\t\v\0"): string| Parameter | Description |
|---|---|
$string | The input string to trim. |
$characters | Optional. The set of characters to strip. Each character is treated individually — order does not matter. When omitted, the default whitespace set is used. |
The function returns a new string; the original is never modified (PHP strings are passed by value).
The default character set
When you call ltrim() with one argument, it removes these characters from the left:
" "(ordinary space)"\t"(tab)"\n"(line feed)"\r"(carriage return)"\0"(NUL byte)"\v"(vertical tab)
Trimming leading whitespace
The most common use is cleaning up leading whitespace:
Output:
[Hello World! ]Notice that the trailing spaces remain — ltrim() only touches the left side. The [ and ] brackets are added just to make the boundaries visible in the output.
Trimming specific characters
Pass a second argument to remove a custom set of characters instead of whitespace. A classic case is stripping leading zeros:
<?php
echo ltrim("0042", "0"); // 42
echo "\n";
echo ltrim("xxxHello", "x"); // Hello
?>Output:
42
HelloThe $characters argument is a set, not a substring. Every listed character is removed independently, so ltrim($line, ".,") strips any combination of leading dots and commas:
<?php
$line = "...,.,Hello, World";
echo ltrim($line, ".,"); // Hello, World
?>Output:
Hello, WorldIt stops at the first character that is not in the set (H here), leaving the inner , in Hello, World untouched.
Common gotchas
- It is not a substring removal.
ltrim("hello", "he")removes bothhandecharacters, returning"llo"— it does not look for the literal prefix"he". To strip a known prefix, usestr_replace()on the first occurrence orsubstr(). - Byte-based, not Unicode-aware.
ltrim()works on bytes, so it can corrupt multibyte UTF-8 characters if you list them in$characters. For ASCII it is perfectly safe; for trimming multibyte characters, use apreg_replace()pattern with theumodifier. - It returns a copy. Assign the result back if you want to keep it:
$s = ltrim($s);.
When to use which trim
| Need | Use |
|---|---|
| Strip from the start only | ltrim() |
| Strip from the end only | rtrim() |
| Strip from both ends | trim() |
For a broader tour of PHP string handling, see PHP Strings.