How to remove white space from a string in PHP

Topic: PHP / MySQL« Prev|Next »

Answer: Use the PHP trim() function

You can use the PHP trim() function to remove whitespace including non-breaking spaces, newlines, and tabs from the beginning and end of the string. It will not remove whitespace occurs in the middle of the string. Here's is an example:

  • <?php
  • $my_str = '    Welcome to Tutorial Republic ';
  • echo strlen($my_str); // Outputs: 33
  •  
  • $trimmed_str = trim($my_str);
  • echo strlen($trimmed_str); // Outputs: 28
  • ?>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.