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, next I will introduce a perfect solution to this problem ....
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. I will introduce a perfect solution to this problem.
| The code is as follows: |
|
|
$ Str = "This line containstliberal rn use of whitespace. nn ";
// Remove the start and end spaces.
$ Str = trim ($ str );
// Remove the blank space crowded with other items
$ Str = preg_replace ('/s (? = S)/', '', $ str );
// Finally, remove the non-space blank and replace it with a space.
$ Str = preg_replace ('/[nrt]/', '', $ str );
Echo"
{$str}";
?> |
In the previous example, all spaces are removed step by step. First, we use the trim () function to remove the gaps between start and end. Then, we use preg_replace () to remove duplicates. S stands for any whitespace. (? =) Indicates forward lookup. It matches only the characters that are followed by the same character as it. Therefore, this regular expression means: "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 returns (r), or tabs (t ). We use a space to replace these.