Mastering PHP's ltrim(): Remove Unwanted Characters from Strings
This article explains how PHP's ltrim() function removes leading whitespace or custom-specified characters from strings, details its parameters and default character set, and provides clear code examples demonstrating default trimming, custom masks, and range-based character removal.
Function Overview
The ltrim() function removes whitespace or specified characters from the beginning of a string in PHP. Its signature is string ltrim(string $str [, string $character_mask]).
Parameters
$str : The input string.
$character_mask (optional): A list of characters to strip. Ranges can be defined with .., e.g., "\x00..\x1F" to remove ASCII control characters.
Return Value
The function returns the trimmed string. If $character_mask is omitted, it removes the following characters: space, tab ( \t), newline ( \n), carriage return ( \r), NUL byte ( \0), and vertical tab ( \x0B).
Examples
<?php
$text = "\t\tThese are a few words :) ... ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);
print "
";
$trimmed = ltrim($text);
var_dump($trimmed);
$trimmed = ltrim($text, " \t.");
var_dump($trimmed);
$clean = ltrim($binary, "\x00..\x1F");
var_dump($clean);
?>The output demonstrates how ltrim() removes leading whitespace by default, how a custom mask can target specific characters, and how a range mask can strip all ASCII control characters.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
