0
0
PhpHow-ToBeginner · 3 min read

How to Trim String in PHP: Syntax and Examples

In PHP, you can remove whitespace or other characters from the beginning and end of a string using the trim() function. It takes the string as input and returns the trimmed version. You can also specify which characters to remove by passing a second optional parameter.
📐

Syntax

The basic syntax of the trim() function is:

  • trim(string $str, string $character_mask = " \t\n\r\0\x0B") : string

Here:

  • $str is the input string to trim.
  • $character_mask is optional and defines which characters to remove from both ends. By default, it removes whitespace characters like space, tab, newline.
php
trim(string $str, string $character_mask = " \t\n\r\0\x0B") : string
💻

Example

This example shows how to use trim() to remove spaces from the start and end of a string.

php
<?php
$original = "  Hello, PHP!  ";
$trimmed = trim($original);
echo "Original: '" . $original . "'\n";
echo "Trimmed: '" . $trimmed . "'\n";

// Using trim with custom characters
$custom = "--Hello--";
$custom_trimmed = trim($custom, "-");
echo "Custom trimmed: '" . $custom_trimmed . "'\n";
?>
Output
Original: ' Hello, PHP! ' Trimmed: 'Hello, PHP!' Custom trimmed: 'Hello'
⚠️

Common Pitfalls

Common mistakes when trimming strings in PHP include:

  • Not realizing trim() only removes characters from the start and end, not inside the string.
  • Forgetting to specify the $character_mask when you want to remove characters other than whitespace.
  • Using trim() on non-string types without converting them first.
php
<?php
// Wrong: expecting trim to remove spaces inside the string
$wrong = " Hello World ";
echo trim($wrong); // Output: 'Hello World' (spaces inside remain)

// Right: use str_replace to remove spaces inside
$right = str_replace(' ', '', $wrong);
echo $right; // Output: 'HelloWorld'
?>
Output
Hello World HelloWorld
📊

Quick Reference

Here is a quick summary of useful PHP trimming functions:

FunctionDescription
trim($str)Removes whitespace or specified characters from both ends
ltrim($str)Removes whitespace or specified characters from the start (left)
rtrim($str)Removes whitespace or specified characters from the end (right)

Key Takeaways

Use trim() to remove unwanted characters from the start and end of a string in PHP.
By default, trim() removes whitespace like spaces, tabs, and newlines.
Specify a second parameter in trim() to remove custom characters.
trim() does not remove characters inside the string, only at the edges.
Use ltrim() or rtrim() to trim only the left or right side respectively.