Clear the whitespace of a string with a PHP regular expression

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

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 contains\tliberal \r\n use of whitespace.\n\n";

// First remove the leading/trailing whitespace
//去掉开始和结束的空白
$str = trim($str);

// Now remove any doubled-up whitespace
//去掉跟随别的挤在一块的空白
$str = preg_replace('/\s(?=\s)/', '', $str);

// Finally, replace any non-space whitespace, with a space
//最后,去掉非space 的空白,用一个空格代替
$str = preg_replace('/[\n\r\t]/', ' ', $str);

// Echo out: 'This line contains liberal 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 represents 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 [\n\r\t] to find any remnants of a newline character (\ n), a carriage return (\ r), or a tab character (\ 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.