How to strip excess whitespace from a string with preg_replace()


PHP provides many pre-defined methods to deal with strings. One of the strong way to deal with strings is to use regular expressions aka ‘regex‘.

Let’s use regular expression with preg_replace() method to strip excess whitespace from a string.

  //the string from where you want to strip excess spaces
  $string = 'This       is the       sting       text';
  //apply regular expression with preg_replace to remove all spaces
  $string = preg_replace('/\s\s+/', ' ', $string);
  //this will print 'This is the string text'
  echo $str;

If you know any other alternative, please post in comments. I’ll add it in this article.

Related posts:

About Sach

Sachin is a web application developer, technology blogger and web addict! He has over 6 years of web development experience and he writes tutorials primarily focused on LAMP, Ajax, Api's, jQuery etc. He is usability expert and he always likes to share his knowledge with people.

, , , , , ,

  • Shubhamoy

    Really cool tutorial! I Googled it but was unable to find a better way.