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.