Removing Whitespace (and Line Breaks)

by | April 30,2015

Table of Contents

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()

Trim() and Line Breaks

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

$text = '   

 Hello     
 
 
 '
$text.Trim()

Customizing Trim() Behavior

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")

ReTweet this Tip!