Clear the whitespace of a string with a PHP regular expression

Source: Internet
Author: User
Tags php regular expression regular expression

We often process data from user input or read from the database, and may have extra blanks or tabs in your string, carriage return, and so on. Storing these extra characters is a bit of a waste of space.

If you want to get rid of the string start and end whitespace you can use the PHP intrinsic function trim (). However, we often want to completely erase the blanks. You need to clear the opening and closing blanks, turn multiple whitespace into a blank, and use a rule to handle other blanks of the same type.

To do this, you can use a regular expression of PHP to complete the

The following example can remove the extra whitespace

<?php
$STR = "This line containstliberal RN with Whitespace.nn";

The leading/trailing whitespace
Remove the start and end blanks
$str = Trim ($STR);

Now remove any doubled-up whitespace
To take the rest of the space and squeeze it in.
$str = Preg_replace ('/s (? =s)/', ', $str);

Finally, replace any non-space whitespace and a space
Finally, remove the blank space, using a space instead
$str = preg_replace ('/[nrt]/', ', ', $str);

Echo out: ' This line contains liberal the use of whitespace. '
echo "<pre>{$str}</pre>";
?>


The example above removes all the blanks in one step. First we use the trim () function to remove the start and end whitespace. Then we use Preg_replace () to remove the duplicates. s stands for any whitespace. (? =) indicates a forward lookup. It smells like only characters that have the same characters that follow it. So this regular expression means: "Any whitespace character followed by the whitespace character." "We replace it with blanks, so we go away, leaving the only whitespace character."

Finally, we use another regular expression [NRT] to find any remnants of the newline character (n), carriage return (r), or tab (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.