Trim () and preg_replace () in php clear string spaces and consecutive spaces

Source: Internet
Author: User
The simplest way to clear spaces in php is to use the trim () function, but this function often fails to reach the desired result. in particular, it cannot be created when the string has characters such as rn, lower

The simplest way to clear spaces in php is to use the trim () function, but this function often fails to achieve what we want, in particular, strings such as \ r \ n cannot be created. The following describes a perfect solution to this problem. The code is as follows:

  1. $ Str = "This line containstliberal rn use of whitespace. nn ";
  2. // Remove the start and end spaces.
  3. $ Str = trim ($ str );
  4. // Remove the blank space crowded with other items
  5. $ Str = preg_replace ('/s (? = S)/', '', $ str );
  6. // Finally, remove the non-space blank and replace it with a space.
  7. $ Str = preg_replace ('/[nrt]/', '', $ str );
  8. Echo"
    {$str}
    ";
  9. ?>

In the previous example, all the white spaces are removed step by step. First, we use the trim () function to remove the white spaces at the beginning and end. then, we use preg_replace () to remove duplicates. s represents any whitespace, (? =) Indicates forward lookup. it matches only the characters that are followed by the same character as itself. Therefore, this regular expression indicates: "Any whitespace character followed by the whitespace character, "We will replace it with a blank space, so that we can remove it, leaving the only whitespace character.

Finally, we use another regular expression [nrt] to find any residual line breaks (n), carriage return (r), or tabs (t). We use a space to replace these.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.