We often process data imported from users or read from the database. There may be excess vacancies or tabs in your strings, and press enter. Storing these extra characters is a waste of space. If you want to start and end the string
We often process data imported from users or read from the database. There may be excess vacancies or tabs in your strings, and press enter. Storing these extra characters is a waste of space.
If you want to drop the gap between the start and end of a string, you can apply the PHP internal function trim (). However, we often want to clear all vacancies. You need to clear the opening and ending vacancies, change multiple vacancies into one, and apply one rule to deal with other vacancies of the same type.
You can use the regular expression of PHP to complete these operations.
In the following example, we can remove the additional Whitespace.
$ Str = 'This line contains \ tliberal \ r \ n use of whitespace. \ n \ n ';
// First remove the leading/trailing whitespace
// Drop the start and end vacancies
$ Str = trim ($ str );
// Now remove any doubled-up whitespace
// Follow other vacancies in the same area
$ Str = preg_replace ('/\ s (? = \ S)/', '', $ str );
// Finally, replace any non-space whitespace, with a space
// Finally, remove non-space vacancies and replace them with a space.
$ Str = preg_replace ('/[\ n \ r \ t]/', '', $ str );
// Echo out: 'This line contains liberal use of whitespace .'
Echo'
{$str}
';
?>
In the previous example, all vacancies are removed step by step. First, we use the trim () function to remove the gap between start and end. Then, we apply preg_replace () to distinct duplicates. \ S represents any whitespace. (? =) Forward lookup. It matches only the characters that are followed by the same character. Therefore, this regular expression indicates any whitespace character followed by the whitespace character. 'The vacancy is used to replace it. in this way, the only whitespace character is left.
Finally, we apply another regular expression [\ n \ r \ t] to find any residual line breaks (\ n), carriage return (\ r), or tabs (\ t ). We use a space to replace these.