In many cases, there are spaces in the string, and these spaces are not what we want to clear. next I will introduce how to use regular expressions to clear white spaces in the string. Use trim series functions to delete left and right spaces nbsp...
In many cases, there are spaces in the string, and these spaces are not what we want to clear. next I will introduce how to use regular expressions to clear white spaces in the string.
Use trim series functions to delete left and right spaces
The code is as follows: |
|
Trim removes spaces at both ends of a string, Rtrim removes the right space of a string, Ltrim removes the left space of a string. Echo trim ("space ")." "; Echo rtrim ("space ")." "; Echo ltrim ("space ")." "; ?> |
You cannot use the php trim () function to delete all spaces, because the class can only remove idle space on both sides.
The code is as follows: |
|
Function trimall ($ str) // delete spaces { $ Qian = array ("", "", "t", "n", "r "); $ Hou = array ("","","","",""); Return str_replace ($ qian, $ hou, $ str ); }
|
You can only delete some common spaces. here is a more specific example.
The code is as follows: |
|
$ Str = "This line containstliberal rn use of whitespace. nn "; // First remove the leading/trailing whitespace // Remove the start and end spaces. $ Str = trim ($ str ); // Now remove any doubled-up whitespace // Remove the blank space crowded with other items $ Str = preg_replace ('/s (? = S)/', '', $ str ); // Finally, replace any non-space whitespace, with a space // Finally, remove the non-space blank and replace it with a space. $ Str = preg_replace ('/[nrt]/', '', $ str ); // Echo out: 'This line contains liberal use of whitespace .' Echo" {$str} "; |
In the middle, replace consecutive and left and right spaces with preg_replace to remove duplicates, and then use another regular expression [nrt] to find any residual line breaks (n ), press enter (r) or tab (t.
Permanent link:
Reprint at will! Include the article address.