ltrim / rtrim
ltrim(string $string, string $characters = " \t\n\r\0\x0B"): string · rtrim(string $string, string $characters = " \t\n\r\0\x0B"): string
Directed trimming: ltrim cuts only the left side and rtrim only the right (same default whitespace set as trim); charlist is a character SET, not a prefix/suffix string — ltrim('Hello, World!', 'He') strips the characters H and e, not the string 'He'.
C C23
#include <stdio.h>
#include <string.h>
/* no trim API: hand-rolled cutset loops (the same set semantics as PHP charlist) */
static const char *ltrim_set(const char *s, const char *set) {
while (*s && strchr(set, (unsigned char)*s)) { s++; }
return s;
}
static void rtrim_set(char *s, const char *set) {
size_t n = strlen(s);
while (n > 0 && strchr(set, (unsigned char)s[n - 1])) { s[--n] = '\0'; }
}
int main(void) {
printf("[%s]\n", ltrim_set(" hello ", " "));
char a[] = " hello ";
rtrim_set(a, " ");
printf("[%s]\n", a);
printf("[%s]\n", ltrim_set("Hello, World!", "He"));
printf("[%s]\n", ltrim_set("abcbcXYZ", "abc"));
char b[] = "test.php";
rtrim_set(b, ".php");
printf("[%s]\n", b);
return 0;
}
[hello ] [ hello] [llo, World!] [XYZ] [test]
C++ C++26
#include <iostream>
#include <string>
// find_first_not_of / find_last_not_of: built-in set semantics (same as PHP charlist)
static std::string ltrim_set(const std::string &s, const std::string &set) {
auto pos = s.find_first_not_of(set);
return s.substr(pos == std::string::npos ? s.size() : pos);
}
static std::string rtrim_set(const std::string &s, const std::string &set) {
auto pos = s.find_last_not_of(set);
return s.substr(0, pos == std::string::npos ? 0 : pos + 1);
}
int main() {
std::cout << "[" << ltrim_set(" hello ", " ") << "]\n";
std::cout << "[" << rtrim_set(" hello ", " ") << "]\n";
std::cout << "[" << ltrim_set("Hello, World!", "He") << "]\n";
std::cout << "[" << ltrim_set("abcbcXYZ", "abc") << "]\n";
std::cout << "[" << rtrim_set("test.php", ".php") << "]\n";
return 0;
}
[hello ] [ hello] [llo, World!] [XYZ] [test]
C# v11.0.100
using System;
// TrimStart/TrimEnd(params char[]): set semantics built in (same as PHP charlist)
Console.WriteLine($"[{" hello ".TrimStart()}]");
Console.WriteLine($"[{" hello ".TrimEnd()}]");
Console.WriteLine($"[{"Hello, World!".TrimStart('H', 'e')}]");
Console.WriteLine($"[{"abcbcXYZ".TrimStart('a', 'b', 'c')}]");
Console.WriteLine($"[{"test.php".TrimEnd('.', 'p', 'h')}]");
[hello ] [ hello] [llo, World!] [XYZ] [test]
Go v1.27.4
package main
import (
"fmt"
"strings"
)
// strings.TrimLeft/TrimRight: cutset is a SET of chars (same as PHP charlist semantics)
func main() {
fmt.Printf("[%s]\n", strings.TrimLeft(" hello ", " "))
fmt.Printf("[%s]\n", strings.TrimRight(" hello ", " "))
fmt.Printf("[%s]\n", strings.TrimLeft("Hello, World!", "He"))
fmt.Printf("[%s]\n", strings.TrimLeft("abcbcXYZ", "abc"))
fmt.Printf("[%s]\n", strings.TrimRight("test.php", ".php"))
}
[hello ] [ hello] [llo, World!] [XYZ] [test]
Java v27.0.1
public class Main {
// no cutset API: strip* is Unicode-whitespace-only; char-set semantics need hand-rolled loops
// (Apache commons-lang3 StringUtils.stripStart/stripEnd in real projects)
static String ltrimSet(String s, String set) {
int i = 0;
while (i < s.length() && set.indexOf(s.charAt(i)) >= 0) i++;
return s.substring(i);
}
static String rtrimSet(String s, String set) {
int i = s.length();
while (i > 0 && set.indexOf(s.charAt(i - 1)) >= 0) i--;
return s.substring(0, i);
}
public static void main(String[] args) {
System.out.println("[" + " hello ".stripLeading() + "]");
System.out.println("[" + " hello ".stripTrailing() + "]");
System.out.println("[" + ltrimSet("Hello, World!", "He") + "]");
System.out.println("[" + ltrimSet("abcbcXYZ", "abc") + "]");
System.out.println("[" + rtrimSet("test.php", ".php") + "]");
}
}
[hello ] [ hello] [llo, World!] [XYZ] [test]
JavaScript v26.13.1
// trimStart/trimEnd strip whitespace only - no charlist: hand-rolled set semantics
const ltrim = (s, set = " \t\n\r\v\f\0") => {
let i = 0;
while (i < s.length && set.includes(s[i])) i++;
return s.slice(i);
};
const rtrim = (s, set = " \t\n\r\v\f\0") => {
let i = s.length;
while (i > 0 && set.includes(s[i - 1])) i--;
return s.slice(0, i);
};
console.log(`[${ltrim(" hello ")}]`);
console.log(`[${rtrim(" hello ")}]`);
console.log(`[${ltrim("Hello, World!", "He")}]`);
console.log(`[${ltrim("abcbcXYZ", "abc")}]`);
console.log(`[${rtrim("test.php", ".php")}]`);
[hello ] [ hello] [llo, World!] [XYZ] [test]
PHP v8.6.0
// whitespace by default, directional: left only / right only
$s = " hello ";
echo "[" . ltrim($s) . "]\n";
echo "[" . rtrim($s) . "]\n";
// charlist is a SET of characters, not a prefix/suffix string
echo "[" . ltrim("Hello, World!", "He") . "]\n"; // H and e stripped from the leading run
echo "[" . ltrim("abcbcXYZ", "abc") . "]\n"; // whole leading run inside the set
echo "[" . rtrim("test.php", ".php") . "]\n"; // trailing chars inside the set
[hello ] [ hello] [llo, World!] [XYZ] [test]
Python v3.15.2
# lstrip/rstrip: the direct counterparts (charlist is a SET, same semantics)
s = " hello "
print(f"[{s.lstrip()}]")
print(f"[{s.rstrip()}]")
print(f"[{'Hello, World!'.lstrip('He')}]") # set of chars, not a prefix string
print(f"[{'abcbcXYZ'.lstrip('abc')}]") # whole leading run inside the set
print(f"[{'test.php'.rstrip('.php')}]")
[hello ] [ hello] [llo, World!] [XYZ] [test]
Rust v1.99.1
fn main() {
// trim_start_matches/trim_end_matches take a char-slice pattern: set semantics built in
println!("[{}]", " hello ".trim_start_matches(&[' ', '\t', '\n', '\r'][..]));
println!("[{}]", " hello ".trim_end_matches(&[' ', '\t', '\n', '\r'][..]));
println!("[{}]", "Hello, World!".trim_start_matches(&['H', 'e'][..]));
println!("[{}]", "abcbcXYZ".trim_start_matches(&['a', 'b', 'c'][..]));
println!("[{}]", "test.php".trim_end_matches(&['.', 'p', 'h'][..]));
}
[hello ] [ hello] [llo, World!] [XYZ] [test]
TypeScript v26.13.1
// trimStart/trimEnd strip whitespace only - no charlist: hand-rolled set semantics
const ltrim = (s: string, set: string = " \t\n\r\v\f\0"): string => {
let i = 0;
while (i < s.length && set.includes(s[i])) i++;
return s.slice(i);
};
const rtrim = (s: string, set: string = " \t\n\r\v\f\0"): string => {
let i = s.length;
while (i > 0 && set.includes(s[i - 1])) i--;
return s.slice(0, i);
};
console.log(`[${ltrim(" hello ")}]`);
console.log(`[${rtrim(" hello ")}]`);
console.log(`[${ltrim("Hello, World!", "He")}]`);
console.log(`[${ltrim("abcbcXYZ", "abc")}]`);
console.log(`[${rtrim("test.php", ".php")}]`);
[hello ] [ hello] [llo, World!] [XYZ] [test]
Language differences
Contrast with the existing trim entry: trim cuts both sides at once, ltrim/rtrim cut one directed side — all three share the same charlist parameter semantics and the default whitespace set " \t\n\r\0\x0B". Set semantics is the biggest teaching point: ltrim("Hello, World!", "He") strips the character SET {H,e}, yielding "llo, World!" — it does not remove the prefix string "He"; ltrim("abcbcXYZ","abc") eats the entire a/b/c leading run ("XYZ"), further proof the decision is per-character membership.
The ten-language landscape (builtin set semantics, descending): Python's lstrip/rstrip is fully isomorphic to PHP (a chars argument set); C# TrimStart/TrimEnd(params char[]); Go strings.TrimLeft/TrimRight(cutset); Rust trim_start_matches(char-slice pattern); C++ find_first_not_of/find_last_not_of — all builtin set semantics. Java's stripLeading/stripTrailing only know Unicode whitespace (a wider set than PHP's default, including U+2028 etc.) with no cutset form (commons-lang3 stripStart/stripEnd fills the gap); JS trimStart/trimEnd likewise only strip whitespace and take no argument (hand-rolled includes loop; the example's default set adds \0 to match PHP's); C has no trimming function at all (hand-rolled strchr loops — note the (unsigned char) cast to avoid negative-index UB).
Unicode details: Java's strip family decides via Character.isWhitespace (U+00A0 is not whitespace, U+2028 is); Python/PHP default sets are ASCII whitespace — the same text containing a no-break space can trim differently across the three. Empty-set edge: an empty charlist trims nothing in PHP; C++ find_first_not_of on an empty set returns npos (the example guards that branch).