Backend Development 4 min read

Using PHP ltrim() to Remove Leading Whitespace and Characters

This article explains PHP's ltrim function, its syntax, optional character mask, and provides code examples showing how to strip leading whitespace or specific characters from strings, along with notes on behavior and related functions.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP ltrim() to Remove Leading Whitespace and Characters

In PHP programming, handling strings often requires removing leading whitespace, which can affect further processing. PHP provides the ltrim function to conveniently strip characters from the left side of a string.

Basic usage: the function signature is string ltrim ( string $str [, string $character_mask ] ) . The first argument is the target string, and the optional second argument specifies a character mask; if omitted, whitespace (space, tab, newline, etc.) is removed.

Example 1 removes leading spaces:

$str = "   Hello, World!";
$str = ltrim($str);
echo $str;

The output is Hello, World! , with the three leading spaces removed.

Example 2 removes a specific character:

$str2 = "-PHP-is-awesome";
$str2 = ltrim($str2, "-");
echo $str2;

The output is PHP-is-awesome , demonstrating removal of the leading hyphen.

The ltrim function returns the processed string, which can be assigned to a new variable or used directly in output. It only affects the left side of the string; to trim both sides, use trim . The function is case‑sensitive; for case‑insensitive removal, convert the string to lower case first.

In summary, PHP’s ltrim function provides an easy way to strip leading whitespace or other characters, facilitating further string manipulation.

BackendPHPstring-manipulationltrimtrim functions
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.