Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP ltrim() function

Reference for PHP ltrim(): remove whitespace or listed characters from the start of a string, strip leading zeros and slashes, and avoid the prefix mistake.

ltrim() removes characters from the left side (the beginning) of a string. By default it strips whitespace; pass a second argument to strip other characters, such as leading zeros or slashes.

It is the left-only sibling of trim() and rtrim(). The end of the string is never changed.

PHP
<?php
echo ltrim("   hi  ") . "|";      // hi  |
echo ltrim("0042", "0");          // 42

Try it

PHP Left-side trimming

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Sets of characters, not prefixes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
ltrim(string $string, string $characters = " \n\r\t\v\x00"): string
Name Description
$string The input string.
$characters Optional characters to remove. A range such as 0..9 is allowed.

Return value: the string without the leading characters. If everything is stripped, the result is an empty string.

Usage notes

  • Default set: space, \t, \n, \r, \v and the NUL byte.
  • Not a prefix remover. ltrim("http://example.com", "http://") strips every leading h, t, p, : and / character, and stops at the first character outside the set. It works for this input only by luck: http://host.test would lose the h of the host name too and become ost.test. Use str_starts_with() and substr() for prefixes.
  • Leading zeros: ltrim("000", "0") gives "", not "0". Cast to int when you want a number.
  • Bytes only; multibyte whitespace is not stripped by default.
  • Normalizing paths: combine with rtrim() to join path pieces safely: rtrim($dir, "/") . "/" . ltrim($file, "/").