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 containstliberal RN with Whitespace.nn";
The leading/trailing whitespace
Remove the start and end blanks
$str = Trim ($STR);
Now remove any doubled-up whitespace
To take the rest of the space and squeeze it in.
$str = Preg_replace ('/s (? =s)/', ', $str);
Finally, replace any non-space whitespace and a space
Finally, remove the blank space, using a space instead
$str = preg_replace ('/[nrt]/', ', ', $str);
Echo out: ' This line contains liberal the 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 stands for 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 [NRT] to find any remnants of the newline character (n), carriage return (r), or tab (t). We use a space to replace these.