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.

php Courses
php Courses
php Courses
Master PHP’s trim(): Remove Unwanted Spaces and Invisible Characters

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.

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.

programmingPHPbackend-development.trimString Manipulation
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.