Removing Whitespace (and Line Breaks)

by Apr 30, 2015

You may know that each string object has a method called Trim() that trims away whitespace both from the beginning and end of a string:

$text = '    Hello     '
$text.Trim()

A lesser known fact is that Trim() will also eat away leading and trailing line breaks:

$text = '   

 Hello     
 
 
 '
$text.Trim()

And if you want, you can make Trim() eat away whatever you want.

This example trims away whitespace, dots, dashes, and line breaks:

$text = '   

 ... Hello     
 
 ...---
 '
$text.Trim(" .-`t`n`r")

Twitter This Tip! ReTweet this Tip!