Master PHP’s trim(): Remove Unwanted Spaces and Invisible Characters
This article explains how PHP's trim() function removes leading and trailing whitespace and other invisible characters from strings, demonstrates its basic usage with code examples, and shows how to customize the characters to strip for flexible string cleaning.
In PHP development, handling strings often requires removing invisible whitespace characters at the ends, which can affect operations and display.
The built‑in trim() function removes whitespace from both ends of a string. Its syntax is simple: pass the target string as the argument.
<?php
$str = " Hello, World! ";
$trimmedStr = trim($str);
echo "Original string: '" . $str . "'
";
echo "Trimmed string: '" . $trimmedStr . "'
";
?>The example defines $str containing leading and trailing spaces, applies trim() to produce $trimmedStr, and outputs both strings.
Running the script yields:
Original string: ' Hello, World! '
Trimmed string: 'Hello, World!'Beyond spaces, trim() can also remove other invisible characters such as newlines and tabs. To specify additional characters, provide a second argument to trim(), e.g., to strip tabs:
<?php
$str = " Hello, World! ";
$trimmedStr = trim($str, " ");
echo "Original string: '" . $str . "'
";
echo "Trimmed string: '" . $trimmedStr . "'
";
?>Thus, trim() is a versatile function for cleaning strings to meet various requirements.
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.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.
