• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / PHP / PHP Strings / Trimming PHP Strings

Trimming PHP Strings

26 November 2009 / 1 Comment

In programming-speak, trimming a string means removing unwanted characters — typically whitespace characters — from either end (or both ends) of the string. This is useful in a number of scenarios, such as:

  • Cleaning up user input, such as text field values in a submitted form
  • Removing unwanted line-break characters at the end of a line
  • Ensuring that a string is in the correct format for passing to another program

In this article you explore 3 useful PHP functions that you can use to trim strings:

  • trim() for trimming both ends of a string
  • ltrim() for trimming the beginning of a string, and
  • rtrim() for trimming the end of a string.

Trimming a string with trim()

PHP’s trim() function removes all whitespace from the beginning and the end of a string. Here’s an example:


$myString = "
                Hello there!
";

// Displays "Hello there!"
echo trim( $myString );
Notice that PHP doesn’t remove the space between "Hello" and "there!". Only whitespace at the start and end of a string are removed.

What is whitespace?

PHP considers the following characters to be whitespace:

  • The space character (" ")
  • The tab character ("\t")
  • The vertical tab character ("\v")
  • The newline character ("\n")
  • The carriage return character ("\r")
  • The null-byte character ("\x0B")

For example:


$myString = " \t\tHello there!\r\n\r\n";

// Displays "Hello there!"
echo trim( $myString );

If you need to trim other characters from the string, you can specify a list of characters to trim as the second argument to trim(). The supplied list replaces the default list of characters. For example, you might want to trim carriage returns and newlines but leave in spaces:


$myString = "\r\r  Hello there!  \n\n";

// Displays "  Hello there!  "
echo trim( $myString, "\r\n" );

You can specify a range of characters using 2-dot (..) notation. The following example trims all space characters and digits:


$myString = "123 Hello there! 456";

// Displays "Hello there!"
echo trim( $myString, " 0..9" );

Trimming either end of a string with ltrim() and rtrim()

PHP’s ltrim() and rtrim() functions work much like trim(), except that they only trim one end of the string:

  • ltrim() removes whitespace only from the start of the string, leaving any whitespace at the end of the string intact.
  • rtrim() does the opposite: it only removes whitespace from the end of the string.

Here are a couple of examples using ltrim() and rtrim():


$myString = "   Hello there!   ";

// Displays "Hello there!   "
echo ltrim( $myString );

$myString = "123 Hello there! 456";

// Displays "123 Hello there!"
echo rtrim( $myString, " 0..9" );

rtrim() in particular is handy for stripping end-of-line characters from a string that was read from a file:


$myString = "Hello there!\r\n";

// Displays "Hello there!"
echo rtrim( $myString, "\r\n" );

In this article you’ve looked at PHP’s trim(), ltrim() and rtrim() functions for removing unwanted characters around a string. You also learned about whitespace characters, and you saw how to specify your own list of whitespace characters when trimming.

Happy coding!

Filed Under: PHP Strings Tagged With: ltrim, php strings, rtrim, trim, whitespace

Reader Interactions

Comments

  1. typing kick says

    28 April 2022 at 5:31 am

    actually I am looking for trimming a newline from anywhere in the paragraph

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits