Skip to Content

How to Trim Characters from a String with PHP

In this tutorial, we'll look into how you can remove whitespace and other characters from a string using the trim() function in PHP.

I find this method particularly useful in cases where an application accepts user input to store in a database. The trim() function removes any whitespace surrounding a string's value, resulting in a correctly stored value in the database table.

Ad - Web Hosting from SiteGround - Crafted for easy site management. Click to learn more.
Advertising Disclosure: I am compensated for purchases made through affiliate links. Click here for details.

What is the PHP trim() Function?

The trim() function in PHP removes whitespace and any other specified characters from both the left and right sides of a string.

Alternatively, you can use the ltrim() function to remove whitespace from only the left side of a string and rtrim() to remove whitespace from only the right side of a string.

Syntax & Parameters

The syntax for the PHP trim() function looks like this:

trim($string, $chars);

Here is a breakdown of each of the parameters:

  • $string: A required, hard-coded string or variable containing the text you want to remove whitespaces or characters.
  • $chars: An optional parameter where you can pass in specific characters to remove. If this parameter is left empty, the function will remove whitespace from both sides of a string by default.

Character Removal Examples

Here are a few examples you can use when passing in a value for the $chars parameter:

  • "\0" - NULL
  • "\n" - Newline
  • "\r" - Carriage return
  • "\t" - Horizontal tab
  • "\x0B" - Vertical tab
  • " " - Whitespace

Code Examples

To remove whitespace from both sides of a string, use the following example:

$string = " This is a string ";
echo trim($string);

The output for the above example will show as follows:

This is a string

You can specify certain characters to remove from a string, as well:

$string = "This is a string";
echo trim($string, "ing");

Resulting in the following output:

This is a str

As you can see, the text "ing" is now omitted from our resulting string, showing a partially removed sentence.

Conclusion

The PHP trim() function provides simple functionality that packs a punch when you need something quick and useful to clean up your data. Alternatively, the ltrim() and rtrim() functions can be used for trimming specific sides of your strings.

Posted by: Josh Rowe
Created: June 10, 2022

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.