Converts big whitespaces into one whitespace


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. $string = 'This string has no whitespaces.';
  3. echo ereg_replace( ' +', '', $string ); //note: before '+' we have 2 spaces
  4. ?>
  5.  
  6. Output: This string has no white spaces.
  7.  
  8. // OR EVEN BETTER
  9.  
  10. trim's code can of course be simplified with some use of the trim() function....
  11.  
  12. <?php
  13. $str = " Words with lots of spaces ";
  14. $str = preg_replace('/\s\s+/', ' ', trim($str));
  15. ?>
  16.  
  17. Doing the trim() first reduces the workload being put on the more expensive preg_replace().

URL: http://us3.php.net/trim

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.