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!";<br>$str = ltrim($str);<br>echo $str;

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

Example 2 removes a specific character:

$str2 = "-PHP-is-awesome";<br>$str2 = ltrim($str2, "-");<br>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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

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

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.