0
0
PHPprogramming~5 mins

Trim functions in PHP

Choose your learning style9 modes available
Introduction

Trim functions help remove unwanted spaces or characters from the start and end of text. This makes the text clean and ready to use.

When you get user input with extra spaces before or after the text.
When reading data from files that may have extra spaces or new lines.
When comparing two texts and you want to ignore spaces around them.
When preparing text to save in a database without extra spaces.
When cleaning up strings before displaying them on a webpage.
Syntax
PHP
trim(string $str, string $characters = " \t\n\r\0\x0B"): string
ltrim(string $str, string $characters = " \t\n\r\0\x0B"): string
rtrim(string $str, string $characters = " \t\n\r\0\x0B"): string

trim() removes characters from both ends of the string.

ltrim() removes characters only from the start (left side).

rtrim() removes characters only from the end (right side).

Examples
Removes spaces from both sides of the string.
PHP
$text = "  hello  ";
$clean = trim($text);
echo "'$clean'";
Removes asterisks (*) from both ends of the string.
PHP
$text = "***hello***";
$clean = trim($text, "*");
echo "'$clean'";
Removes spaces only from the start (left side).
PHP
$text = "  hello  ";
$cleanLeft = ltrim($text);
echo "'$cleanLeft'";
Removes spaces only from the end (right side).
PHP
$text = "  hello  ";
$cleanRight = rtrim($text);
echo "'$cleanRight'";
Sample Program

This program shows how trim(), ltrim(), and rtrim() work on a string with spaces and special characters. It also shows removing custom characters like asterisks.

PHP
<?php
// Example showing trim functions
$input = "  \tHello World!\n  ";

echo "Original: '" . $input . "'\n";

$trimmed = trim($input);
echo "Trimmed: '" . $trimmed . "'\n";

$leftTrimmed = ltrim($input);
echo "Left Trimmed: '" . $leftTrimmed . "'\n";

$rightTrimmed = rtrim($input);
echo "Right Trimmed: '" . $rightTrimmed . "'\n";

// Using trim to remove custom characters
$custom = "***Hello***";
$customTrimmed = trim($custom, "*");
echo "Custom Trimmed: '" . $customTrimmed . "'\n";
?>
OutputSuccess
Important Notes

By default, trim removes spaces, tabs, new lines, and some other whitespace characters.

You can specify which characters to remove by passing them as the second argument.

Trim functions do not change the original string; they return a new trimmed string.

Summary

Trim functions clean text by removing unwanted characters from the start and/or end.

Use trim() for both ends, ltrim() for left only, and rtrim() for right only.

They help prepare text for storage, comparison, or display.