How do I replace tabs with spaces within variables in PHP?

Arthur picture Arthur · Jul 25, 2009 · Viewed 47.1k times · Source

$data contains tabs, leading spaces and multiple spaces. I wish to replace all tabs with a space. Multiple spaces with one single space, and remove leading spaces.

In fact somthing that would turn this input data:

[    asdf asdf     asdf           asdf   ] 

Into output data:

[asdf asdf asdf asdf]

How do I do this?

Answer

ahc picture ahc · Jul 25, 2009

Trim, replace tabs and extra spaces with single spaces:

$data = preg_replace('/[ ]{2,}|[\t]/', ' ', trim($data));