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 echo ltrim(" hi ") . "|"; // hi | echo ltrim("0042", "0"); // 42
Try it
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.
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
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,\vand the NUL byte. - Not a prefix remover.
ltrim("http://example.com", "http://")strips every leadingh,t,p,:and/character, and stops at the first character outside the set. It works for this input only by luck:http://host.testwould lose thehof the host name too and becomeost.test. Usestr_starts_with()andsubstr()for prefixes. - Leading zeros:
ltrim("000", "0")gives"", not"0". Cast tointwhen 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, "/").
Related
trim(),rtrim(),substr(),str_starts_with()- Lessons: Strings, String functions