PHP USES regular expressions to clear whitespaces in strings

  • 2020-03-31 21:26:11
  • OfStack

If you want to remove whitespaces from the beginning and end of a string, you can use the PHP internal function trim(). However, we often want to clear the white space completely. You need to clear the start and end whitespace, turn multiple whitespace into one, and use a rule to handle other whitespace of the same type.

This can be done using PHP's regular expressions

The following example removes the additional Whitespace
 
<?php 
$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 white space that follows the others
$str = preg_replace('/s(?=s)/', '', $str); 

// Finally, replace any non-space whitespace, with a space 
//Finally, remove the non-space space and replace it with a space
$str = preg_replace('/[nrt]/', ' ', $str); 

// Echo out: 'This line contains liberal use of whitespace.' 
echo "<pre>{$str}</pre>"; 
?> 


Step by step, remove all the white space. First we use the trim() function to remove the start and end whitespaces. We then remove the duplicate using preg_replace(). \s stands for any whitespace. (? =) means look forward. It means matching only characters that are followed by the same character as itself. So this regular expression means: "any whitespace character followed by the whitespace character." We replace it with whitespace so that it is removed, leaving the only whitespace character.

Finally, we use another regular expression [\n\r\t] to find any residual newline character (\n), carriage return (\r), or TAB character (\t). Let's replace these with a space.

Related articles: