Bootstrap FreeKB - PHP - Remove whitespace using trim, ltrim and rtrim
PHP - Remove whitespace using trim, ltrim and rtrim

Updated:   |  PHP articles

In PHP, there are 3 similar built in functions that can be used to remove whitespace.

  • trim - remove whitespace from both the left side and right side of a string 
  • ltrim - remove whitespace from the left side of a string 
  • rtrim - remove whitespace from the right side of a string 

Take for example the following PHP, where there is whitespace to the left and right of Hello World. var_dump is used to show the $foo variable.

<?php
  $foo = " Hello World ";
  var_dump ($foo);
?>

 

Which should return something like this.

string(13) " Hello World "

 

Here is how you could use trim to remove the whitespace to the left and right of Hello World.

<?php
  $foo = " Hello World ";
  $foo = trim($foo);
  var_dump ($foo);
?>

 

Which should now return something like this.

string(11) "Hello World"



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter daf623 in the box below so that we can be sure you are a human.