PHP TUTORIAL

PHP Remove white space


In many cases you want to remove white spaces. A practical example is a php form where you may want to remove the white spaces before you may want to compare the results. Here are some of the options available to you.

1. Use trim() to remove the whitespace at the beginning or at the end of a string. See the example below.
  1. <?php
  2. $str1 = " referencedesigner.com ";
  3. $strtocompare ="referencedesigner.com";
  4. if (trim($str1) == $strtocompare) // True
  5. echo "match is found" ; // Prints this one
  6. else echo "match is not found" ;
  7. ?>
  8.  


2. If you are need to remove the whitespace only at the begining of the string you may want to use ltrim() or rtrim() method. See the two examples below.

  1. <?php
  2. $str1 = " referencedesigner.com";
  3. $strtocompare ="referencedesigner.com";
  4. if (ltrim($str1) == $strtocompare) // True
  5. echo "match is found" ; // Prints this one
  6. else echo "match is not found" ;
  7. ?>
  8.  




  1. <?php
  2. $str1 = "referencedesigner.com "; // notice the space on the right
  3. $strtocompare ="referencedesigner.com";
  4. if (rtrim($str1) == $strtocompare) // True
  5. echo "match is found" ; // Prints this one
  6. else echo "match is not found" ;
  7. ?>
  8.  


3. If you want to replace multiple white spaces that may lie at the beginning, end of middle, you can use the following string replacement metthod. $str = str_replace(' ','',$str);

Check the example below

  1. <?php
  2. $str1 = " ref erenced esigner.com ";
  3. $strtocompare ="referencedesigner.com";
  4.  
  5. if (str_replace(' ','',$str1) ==$strtocompare) // True
  6. echo "match is found" ; // Prints this one
  7. else echo "match is not found" ;
  8. ?>
  9.  


4. You can use the following regular expression to finy any whitespace like new line, tab, space .

preg_replace( '/\s+/', '', $str1 ); // replace all white spaces in the string $str1 The example below shows the usage of this .

  1. <?php
  2. $str1 = " ref erenced
  3. esigner.com ";
  4. $strtocompare ="referencedesigner.com";
  5.  
  6.  
  7. if ( preg_replace( '/\s+/', '', $str1 ) == $strtocompare) // True
  8. echo "match is found" ; // Prints this one
  9. else echo "match is not found" ;
  10. ?>
  11.